More updates for NFAS span/channel mapping
[asterisk/asterisk.git] / channels / chan_zap.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Zaptel Pseudo TDM interface 
5  * 
6  * Copyright (C) 2003 - 2005, Digium, Inc.
7  *
8  * Mark Spencer <markster@digium.com>
9  *
10  * This program is free software, distributed under the terms of
11  * the GNU General Public License
12  */
13
14 #include <stdio.h>
15 #include <string.h>
16 #include "asterisk/lock.h"
17 #include "asterisk/channel.h"
18 #include "asterisk/config.h"
19 #include "asterisk/logger.h"
20 #include "asterisk/module.h"
21 #include "asterisk/pbx.h"
22 #include "asterisk/options.h"
23 #include "asterisk/file.h"
24 #include "asterisk/ulaw.h"
25 #include "asterisk/alaw.h"
26 #include "asterisk/callerid.h"
27 #include "asterisk/adsi.h"
28 #include "asterisk/cli.h"
29 #include "asterisk/cdr.h"
30 #include "asterisk/features.h"
31 #include "asterisk/musiconhold.h"
32 #include "asterisk/say.h"
33 #include "asterisk/tdd.h"
34 #include "asterisk/app.h"
35 #include "asterisk/dsp.h"
36 #include "asterisk/astdb.h"
37 #include "asterisk/manager.h"
38 #include "asterisk/causes.h"
39 #include "asterisk/term.h"
40 #include "asterisk/utils.h"
41 #include "asterisk/transcap.h"
42 #include <sys/signal.h>
43 #include <errno.h>
44 #include <stdlib.h>
45 #if !defined(SOLARIS) && !defined(__FreeBSD__)
46 #include <stdint.h>
47 #endif
48 #include <unistd.h>
49 #include <sys/ioctl.h>
50 #ifdef __linux__
51 #include <linux/zaptel.h>
52 #else
53 #include <zaptel.h>
54 #endif /* __linux__ */
55 #include <math.h>
56 #include <tonezone.h>
57 #include <ctype.h>
58 #ifdef ZAPATA_PRI
59 #include <libpri.h>
60 #ifndef PRI_FACILITY_ENABLE
61 #error "You need newer libpri"
62 #endif
63 #endif
64 #ifdef ZAPATA_R2
65 #include <libmfcr2.h>
66 #endif
67
68 #include "asterisk.h"
69
70 #ifndef ZT_SIG_EM_E1
71 #error "Your zaptel is too old.  please cvs update"
72 #endif
73
74 #ifndef ZT_TONEDETECT
75 /* Work around older code with no tone detect */
76 #define ZT_EVENT_DTMFDOWN 0
77 #define ZT_EVENT_DTMFUP 0
78 #endif
79
80 /*
81  * Define ZHONE_HACK to cause us to go off hook and then back on hook when
82  * the user hangs up to reset the state machine so ring works properly.
83  * This is used to be able to support kewlstart by putting the zhone in
84  * groundstart mode since their forward disconnect supervision is entirely
85  * broken even though their documentation says it isn't and their support
86  * is entirely unwilling to provide any assistance with their channel banks
87  * even though their web site says they support their products for life.
88  */
89
90 /* #define ZHONE_HACK */
91
92 /*
93  * Define if you want to check the hook state for an FXO (FXS signalled) interface
94  * before dialing on it.  Certain FXO interfaces always think they're out of
95  * service with this method however.
96  */
97 /* #define ZAP_CHECK_HOOKSTATE */
98
99 /* Typically, how many rings before we should send Caller*ID */
100 #define DEFAULT_CIDRINGS 1
101
102 #define CHANNEL_PSEUDO -12
103
104 #define AST_LAW(p) (((p)->law == ZT_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
105
106 static const char desc[] = "Zapata Telephony"
107 #ifdef ZAPATA_PRI
108                " w/PRI"
109 #endif
110 #ifdef ZAPATA_R2
111                " w/R2"
112 #endif
113 ;
114
115 static const char tdesc[] = "Zapata Telephony Driver"
116 #ifdef ZAPATA_PRI
117                " w/PRI"
118 #endif
119 #ifdef ZAPATA_R2
120                " w/R2"
121 #endif
122 ;
123
124 static const char type[] = "Zap";
125 static const char config[] = "zapata.conf";
126
127 #define SIG_EM          ZT_SIG_EM
128 #define SIG_EMWINK      (0x100000 | ZT_SIG_EM)
129 #define SIG_FEATD       (0x200000 | ZT_SIG_EM)
130 #define SIG_FEATDMF     (0x400000 | ZT_SIG_EM)
131 #define SIG_FEATB       (0x800000 | ZT_SIG_EM)
132 #define SIG_E911        (0x1000000 | ZT_SIG_EM)
133 #define SIG_FEATDMF_TA  (0x2000000 | ZT_SIG_EM)
134 #define SIG_FXSLS       ZT_SIG_FXSLS
135 #define SIG_FXSGS       ZT_SIG_FXSGS
136 #define SIG_FXSKS       ZT_SIG_FXSKS
137 #define SIG_FXOLS       ZT_SIG_FXOLS
138 #define SIG_FXOGS       ZT_SIG_FXOGS
139 #define SIG_FXOKS       ZT_SIG_FXOKS
140 #define SIG_PRI         ZT_SIG_CLEAR
141 #define SIG_R2          ZT_SIG_CAS
142 #define SIG_SF          ZT_SIG_SF
143 #define SIG_SFWINK      (0x100000 | ZT_SIG_SF)
144 #define SIG_SF_FEATD    (0x200000 | ZT_SIG_SF)
145 #define SIG_SF_FEATDMF  (0x400000 | ZT_SIG_SF)
146 #define SIG_SF_FEATB    (0x800000 | ZT_SIG_SF)
147 #define SIG_EM_E1       ZT_SIG_EM_E1
148 #define SIG_GR303FXOKS   (0x100000 | ZT_SIG_FXOKS)
149 #define SIG_GR303FXSKS   (0x200000 | ZT_SIG_FXSKS)
150
151 #define NUM_SPANS               32
152 #define NUM_DCHANS              4               /* No more than 4 d-channels */
153 #define MAX_CHANNELS    672             /* No more than a DS3 per trunk group */
154
155 #define CHAN_PSEUDO     -2
156
157 #define DCHAN_PROVISIONED (1 << 0)
158 #define DCHAN_NOTINALARM  (1 << 1)
159 #define DCHAN_UP          (1 << 2)
160
161 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
162
163 static int cur_emdigitwait = 250; /* Wait time in ms for digits on EM channel */
164
165 static char context[AST_MAX_EXTENSION] = "default";
166 static char cid_num[256] = "";
167 static char cid_name[256] = "";
168 static char defaultcic[64] = "";
169 static char defaultozz[64] = "";
170
171 static char language[MAX_LANGUAGE] = "";
172 static char musicclass[MAX_LANGUAGE] = "";
173 static char progzone[10]= "";
174
175 static int usedistinctiveringdetection = 0;
176
177 static int use_callerid = 1;
178 static int cid_signalling = CID_SIG_BELL;
179 static int cid_start = CID_START_RING;
180 static int zaptrcallerid = 0;
181 static int cur_signalling = -1;
182
183 static ast_group_t cur_group = 0;
184 static ast_group_t cur_callergroup = 0;
185 static ast_group_t cur_pickupgroup = 0;
186 static int relaxdtmf = 0;
187
188 static int immediate = 0;
189
190 static int stripmsd = 0;
191
192 static int callwaiting = 0;
193
194 static int callwaitingcallerid = 0;
195
196 static int hidecallerid = 0;
197
198 static int restrictcid = 0;
199
200 static int use_callingpres = 0;
201
202 static int callreturn = 0;
203
204 static int threewaycalling = 0;
205
206 static int transfer = 0;
207
208 static int canpark = 0;
209
210 static int cancallforward = 0;
211
212 static float rxgain = 0.0;
213
214 static float txgain = 0.0;
215
216 static int tonezone = -1;
217
218 static int echocancel;
219
220 static int echotraining;
221
222 static int pulse;
223
224 static int echocanbridged = 0;
225
226 static int busydetect = 0;
227
228 static int busycount = 3;
229
230 static int callprogress = 0;
231
232 static char accountcode[20] = "";
233
234 static char mailbox[AST_MAX_EXTENSION];
235
236 static int amaflags = 0;
237
238 static int adsi = 0;
239
240 static int numbufs = 4;
241
242 static int cur_prewink = -1;
243 static int cur_preflash = -1;
244 static int cur_wink = -1;
245 static int cur_flash = -1;
246 static int cur_start = -1;
247 static int cur_rxwink = -1;
248 static int cur_rxflash = -1;
249 static int cur_debounce = -1;
250
251 static int priindication_oob = 0;
252
253 #ifdef ZAPATA_PRI
254 static int minunused = 2;
255 static int minidle = 0;
256 static char idleext[AST_MAX_EXTENSION];
257 static char idledial[AST_MAX_EXTENSION];
258 static int overlapdial = 0;
259 static int facilityenable = 0;
260 static char internationalprefix[10] = "";
261 static char nationalprefix[10] = "";
262 static char localprefix[20] = "";
263 static char privateprefix[20] = "";
264 static char unknownprefix[20] = "";
265 static long resetinterval = 3600;                       /* How often (in seconds) to reset unused channels. Default 1 hour. */
266 static struct ast_channel inuse = { "GR-303InUse" };
267 #ifdef PRI_GETSET_TIMERS
268 static int pritimers[PRI_MAX_TIMERS];
269 #endif
270 #endif
271
272 /* Wait up to 16 seconds for first digit (FXO logic) */
273 static int firstdigittimeout = 16000;
274
275 /* How long to wait for following digits (FXO logic) */
276 static int gendigittimeout = 8000;
277
278 /* How long to wait for an extra digit, if there is an ambiguous match */
279 static int matchdigittimeout = 3000;
280
281 static int usecnt =0;
282 AST_MUTEX_DEFINE_STATIC(usecnt_lock);
283
284 /* Protect the interface list (of zt_pvt's) */
285 AST_MUTEX_DEFINE_STATIC(iflock);
286
287
288 static int ifcount = 0;
289
290 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
291 static int pridebugfd = -1;
292 static char pridebugfilename[1024]="";
293
294 /* Whether we answer on a Polarity Switch event */
295 static int answeronpolarityswitch = 0;
296
297 /* Whether we hang up on a Polarity Switch event */
298 static int hanguponpolarityswitch = 0;
299
300 /* How long (ms) to ignore Polarity Switch events after we answer a call */
301 static int polarityonanswerdelay = 600;
302
303 /* When to send the CallerID signals (rings) */
304 static int sendcalleridafter = DEFAULT_CIDRINGS;
305
306 /* Protect the monitoring thread, so only one process can kill or start it, and not
307    when it's doing something critical. */
308 AST_MUTEX_DEFINE_STATIC(monlock);
309
310 /* This is the thread for the monitor which checks for input on the channels
311    which are not currently in use.  */
312 static pthread_t monitor_thread = AST_PTHREADT_NULL;
313
314 static int restart_monitor(void);
315
316 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
317
318 static int zt_sendtext(struct ast_channel *c, const char *text);
319
320 static inline int zt_get_event(int fd)
321 {
322         /* Avoid the silly zt_getevent which ignores a bunch of events */
323         int j;
324         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
325         return j;
326 }
327
328 static inline int zt_wait_event(int fd)
329 {
330         /* Avoid the silly zt_waitevent which ignores a bunch of events */
331         int i,j=0;
332         i = ZT_IOMUX_SIGEVENT;
333         if (ioctl(fd, ZT_IOMUX, &i) == -1) return -1;
334         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
335         return j;
336 }
337
338 /* Chunk size to read -- we use 20ms chunks to make things happy.  */   
339 #define READ_SIZE 160
340
341 #define MASK_AVAIL              (1 << 0)                /* Channel available for PRI use */
342 #define MASK_INUSE              (1 << 1)                /* Channel currently in use */
343
344 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /* 300 ms */
345 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /* 300 ms */
346 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /* 500 ms */
347 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /* 2000 ms */
348 #define RINGT                                           ( (8000 * 8) / READ_SIZE)
349
350 struct zt_pvt;
351
352
353 #ifdef ZAPATA_R2
354 static int r2prot = -1;
355 #endif
356
357
358 #ifdef ZAPATA_PRI
359
360 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8))
361 #define PRI_CHANNEL(p) ((p) & 0xff)
362 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
363 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
364
365 struct zt_pri {
366         pthread_t master;                                               /* Thread of master */
367         ast_mutex_t lock;                                               /* Mutex */
368         char idleext[AST_MAX_EXTENSION];                /* Where to idle extra calls */
369         char idlecontext[AST_MAX_EXTENSION];    /* What context to use for idle */
370         char idledial[AST_MAX_EXTENSION];               /* What to dial before dumping */
371         int minunused;                                                  /* Min # of channels to keep empty */
372         int minidle;                                                    /* Min # of "idling" calls to keep active */
373         int nodetype;                                                   /* Node type */
374         int switchtype;                                                 /* Type of switch to emulate */
375         int nsf;                                                                /* Network-Specific Facilities */
376         int dialplan;                                                   /* Dialing plan */
377         int localdialplan;                                              /* Local dialing plan */
378         char internationalprefix[10];                   /* country access code ('00' for european dialplans) */
379         char nationalprefix[10];                                /* area access code ('0' for european dialplans) */
380         char localprefix[20];                                   /* area access code + area code ('0'+area code for european dialplans) */
381         char privateprefix[20];                                 /* for private dialplans */
382         char unknownprefix[20];                                 /* for unknown dialplans */
383         int dchannels[NUM_DCHANS];                              /* What channel are the dchannels on */
384         int trunkgroup;                                                 /* What our trunkgroup is */
385         int mastertrunkgroup;                                   /* What trunk group is our master */
386         int prilogicalspan;                                             /* Logical span number within trunk group */
387         int numchans;                                                   /* Num of channels we represent */
388         int overlapdial;                                                /* In overlap dialing mode */
389         int facilityenable;                                             /* Enable facility IEs */
390         struct pri *dchans[NUM_DCHANS];                 /* Actual d-channels */
391         int dchanavail[NUM_DCHANS];                             /* Whether each channel is available */
392         struct pri *pri;                                                /* Currently active D-channel */
393         int debug;
394         int fds[NUM_DCHANS];                                    /* FD's for d-channels */
395         int offset;
396         int span;
397         int resetting;
398         int resetpos;
399         time_t lastreset;                                               /* time when unused channels were last reset */
400         long resetinterval;                                             /* Interval (in seconds) for resetting unused channels */
401         struct zt_pvt *pvts[MAX_CHANNELS];              /* Member channel pvt structs */
402         struct zt_pvt *crvs;                                    /* Member CRV structs */
403         struct zt_pvt *crvend;                                  /* Pointer to end of CRV structs */
404 };
405
406
407 static struct zt_pri pris[NUM_SPANS];
408
409 static int pritype = PRI_CPE;
410
411 #if 0
412 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
413 #else
414 #define DEFAULT_PRI_DEBUG 0
415 #endif
416
417 static inline void pri_rel(struct zt_pri *pri)
418 {
419         ast_mutex_unlock(&pri->lock);
420 }
421
422 static int switchtype = PRI_SWITCH_NI2;
423 static int nsf = PRI_NSF_NONE;
424 static int dialplan = PRI_NATIONAL_ISDN + 1;
425 static int localdialplan = PRI_NATIONAL_ISDN + 1;
426
427 #else
428 /* Shut up the compiler */
429 struct zt_pri;
430 #endif
431
432 #define SUB_REAL                0                       /* Active call */
433 #define SUB_CALLWAIT    1                       /* Call-Waiting call on hold */
434 #define SUB_THREEWAY    2                       /* Three-way call */
435
436 /* Polarity states */
437 #define POLARITY_IDLE   0
438 #define POLARITY_REV    1
439
440
441 static struct zt_distRings drings;
442
443 struct distRingData {
444         int ring[3];
445 };
446 struct ringContextData {
447         char contextData[AST_MAX_EXTENSION];
448 };
449 struct zt_distRings {
450         struct distRingData ringnum[3];
451         struct ringContextData ringContext[3];
452 };
453
454 static char *subnames[] = {
455         "Real",
456         "Callwait",
457         "Threeway"
458 };
459
460 struct zt_subchannel {
461         int zfd;
462         struct ast_channel *owner;
463         int chan;
464         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
465         struct ast_frame f;             /* One frame for each channel.  How did this ever work before? */
466         int needringing;
467         int needbusy;
468         int needcongestion;
469         int needcallerid;
470         int needanswer;
471         int needflash;
472         int linear;
473         int inthreeway;
474         ZT_CONFINFO curconf;
475 };
476
477 #define CONF_USER_REAL          (1 << 0)
478 #define CONF_USER_THIRDCALL     (1 << 1)
479
480 #define MAX_SLAVES      4
481
482 static struct zt_pvt {
483         ast_mutex_t lock;
484         struct ast_channel *owner;      /* Our current active owner (if applicable) */
485                 /* Up to three channels can be associated with this call */
486                 
487         struct zt_subchannel sub_unused;        /* Just a safety precaution */
488         struct zt_subchannel subs[3];   /* Sub-channels */
489         struct zt_confinfo saveconf;    /* Saved conference info */
490
491         struct zt_pvt *slaves[MAX_SLAVES];      /* Slave to us (follows our conferencing) */
492         struct zt_pvt *master;  /* Master to us (we follow their conferencing) */
493         int inconference;               /* If our real should be in the conference */
494         
495         int sig;                                        /* Signalling style */
496         int radio;                              /* radio type */
497         int firstradio;                         /* first radio flag */
498         float rxgain;
499         float txgain;
500         int tonezone;                           /* tone zone for this chan, or -1 for default */
501         struct zt_pvt *next;                    /* Next channel in list */
502         struct zt_pvt *prev;                    /* Prev channel in list */
503
504         struct zt_distRings drings;
505         int usedistinctiveringdetection;
506
507         char context[AST_MAX_EXTENSION];
508         char defcontext[AST_MAX_EXTENSION];
509         char exten[AST_MAX_EXTENSION];
510         char language[MAX_LANGUAGE];
511         char musicclass[MAX_LANGUAGE];
512         char cid_num[AST_MAX_EXTENSION];
513         int cid_ton;                            /* Type Of Number (TON) */
514         char cid_name[AST_MAX_EXTENSION];
515         char lastcid_num[AST_MAX_EXTENSION];
516         char lastcid_name[AST_MAX_EXTENSION];
517         char *origcid_num;                      /* malloced original callerid */
518         char *origcid_name;                     /* malloced original callerid */
519         char callwait_num[AST_MAX_EXTENSION];
520         char callwait_name[AST_MAX_EXTENSION];
521         char rdnis[AST_MAX_EXTENSION];
522         char dnid[AST_MAX_EXTENSION];
523         unsigned int group;
524         int law;
525         int confno;                                     /* Our conference */
526         int confusers;                          /* Who is using our conference */
527         int propconfno;                         /* Propagated conference number */
528         ast_group_t callgroup;
529         ast_group_t pickupgroup;
530         int immediate;                          /* Answer before getting digits? */
531         int channel;                            /* Channel Number or CRV */
532         int span;                                       /* Span number */
533         int dialing;
534         time_t guardtime;                       /* Must wait this much time before using for new call */
535         int dialednone;
536         int use_callerid;                       /* Whether or not to use caller id on this channel */
537         int cid_signalling;                     /* CID signalling type bell202 or v23 */
538         int cid_start;                          /* CID start indicator, polarity or ring */
539         int hidecallerid;
540         int callreturn;
541         int permhidecallerid;           /* Whether to hide our outgoing caller ID or not */
542         int restrictcid;                        /* Whether restrict the callerid -> only send ANI */
543         int use_callingpres;            /* Whether to use the callingpres the calling switch sends */
544         int callingpres;                        /* The value of callling presentation that we're going to use when placing a PRI call */
545         int callwaitingrepeat;          /* How many samples to wait before repeating call waiting */
546         int cidcwexpire;                        /* When to expire our muting for CID/CW */
547         unsigned char *cidspill;
548         int cidpos;
549         int cidlen;
550         int ringt;
551         int stripmsd;
552         int callwaiting;
553         int callwaitcas;
554         int callwaitrings;
555         int echocancel;
556         int echotraining;
557         int pulse;
558         int echocanbridged;
559         int echocanon;
560         int echobreak;
561         char echorest[20];
562         int permcallwaiting;
563         int callwaitingcallerid;
564         int threewaycalling;
565         int transfer;
566         int canpark;
567         int digital;
568         int outgoing;
569         int dnd;
570         int busydetect;
571         int busycount;
572         int callprogress;
573         int priindication_oob;
574         struct timeval flashtime;       /* Last flash-hook time */
575         struct ast_dsp *dsp;
576         int cref;                                       /* Call reference number */
577         ZT_DIAL_OPERATION dop;
578         int whichwink;                  /* SIG_FEATDMF_TA Which wink are we on? */
579         char finaldial[64];
580         int destroy;
581         int ignoredtmf;                         
582         int inalarm;
583         char accountcode[20];           /* Account code */
584         int amaflags;                           /* AMA Flags */
585         char didtdd;                            /* flag to say its done it once */
586         struct tdd_state *tdd;          /* TDD flag */
587         int adsi;
588         int cancallforward;
589         char call_forward[AST_MAX_EXTENSION];
590         char mailbox[AST_MAX_EXTENSION];
591         char dialdest[256];
592         int onhooktime;
593         int msgstate;
594         
595         int confirmanswer;                      /* Wait for '#' to confirm answer */
596         int distinctivering;            /* Which distinctivering to use */
597         int cidrings;                           /* Which ring to deliver CID on */
598         
599         int faxhandled;                         /* Has a fax tone already been handled? */
600         
601         char mate;                                      /* flag to say its in MATE mode */
602         int pulsedial;                          /* whether a pulse dial phone is detected */
603         int dtmfrelax;                          /* whether to run in relaxed DTMF mode */
604         int fake_event;
605         int zaptrcallerid;                      /* should we use the callerid from incoming call on zap transfer or not */
606         int emdigitwait;
607         int answeronpolarityswitch;
608         int hanguponpolarityswitch;
609         int polarityonanswerdelay;
610         struct timeval polaritydelaytv;
611         int sendcalleridafter;
612 #ifdef ZAPATA_PRI
613         struct zt_pri *pri;
614         struct zt_pvt *bearer;
615         struct zt_pvt *realcall;
616         q931_call *call;
617         int isidlecall;
618         int resetting;
619         int prioffset;
620         int logicalspan;
621         int alreadyhungup;
622         int proceeding;
623         int alerting;
624         int setup_ack;                          /* whether we received SETUP_ACKNOWLEDGE or not */
625         int dsp_features;
626 #endif  
627 #ifdef ZAPATA_R2
628         int r2prot;
629         mfcr2_t *r2;
630         int hasr2call;
631         int r2blocked;
632         int sigchecked;
633 #endif  
634         int polarity;
635 } *iflist = NULL, *ifend = NULL;
636
637 static struct ast_channel *zt_request(const char *type, int format, void *data, int *cause);
638 static int zt_digit(struct ast_channel *ast, char digit);
639 static int zt_sendtext(struct ast_channel *c, const char *text);
640 static int zt_call(struct ast_channel *ast, char *rdest, int timeout);
641 static int zt_hangup(struct ast_channel *ast);
642 static int zt_answer(struct ast_channel *ast);
643 struct ast_frame *zt_read(struct ast_channel *ast);
644 static int zt_write(struct ast_channel *ast, struct ast_frame *frame);
645 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
646 struct ast_frame *zt_exception(struct ast_channel *ast);
647 static int zt_indicate(struct ast_channel *chan, int condition);
648 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
649 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen);
650
651 static const struct ast_channel_tech zap_tech = {
652         .type = type,
653         .description = tdesc,
654         .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW,
655         .requester = zt_request,
656         .send_digit = zt_digit,
657         .send_text = zt_sendtext,
658         .call = zt_call,
659         .hangup = zt_hangup,
660         .answer = zt_answer,
661         .read = zt_read,
662         .write = zt_write,
663         .bridge = zt_bridge,
664         .exception = zt_exception,
665         .indicate = zt_indicate,
666         .fixup = zt_fixup,
667         .setoption = zt_setoption,
668 };
669
670 #ifdef ZAPATA_PRI
671 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
672 #else
673 #define GET_CHANNEL(p) ((p)->channel)
674 #endif
675
676 struct zt_pvt *round_robin[32];
677
678 #ifdef ZAPATA_PRI
679 static inline int pri_grab(struct zt_pvt *pvt, struct zt_pri *pri)
680 {
681         int res;
682         /* Grab the lock first */
683         do {
684             res = ast_mutex_trylock(&pri->lock);
685                 if (res) {
686                         ast_mutex_unlock(&pvt->lock);
687                         /* Release the lock and try again */
688                         usleep(1);
689                         ast_mutex_lock(&pvt->lock);
690                 }
691         } while(res);
692         /* Then break the poll */
693         pthread_kill(pri->master, SIGURG);
694         return 0;
695 }
696 #endif
697
698 #define NUM_CADENCE_MAX 25
699 static int num_cadence = 4;
700 static int user_has_defined_cadences = 0;
701
702 static struct zt_ring_cadence cadences[NUM_CADENCE_MAX] = {
703         { { 125, 125, 2000, 4000 } },                   /* Quick chirp followed by normal ring */
704         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /* British style ring */
705         { { 125, 125, 125, 125, 125, 4000 } },  /* Three short bursts */
706         { { 1000, 500, 2500, 5000 } },  /* Long ring */
707 };
708
709 int receivedRingT; /* Used to find out what ringtone we are on */
710
711 /* cidrings says in which pause to transmit the cid information, where the first pause
712  * is 1, the second pause is 2 and so on.
713  */
714
715 static int cidrings[NUM_CADENCE_MAX] = {
716         2,                                                                              /* Right after first long ring */
717         4,                                                                              /* Right after long part */
718         3,                                                                              /* After third chirp */
719         2,                                                                              /* Second spell */
720 };
721
722 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
723                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
724
725 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
726 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __ZT_SIG_FXO) */)
727
728 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
729 {
730         int res;
731         if (p->subs[0].owner == ast)
732                 res = 0;
733         else if (p->subs[1].owner == ast)
734                 res = 1;
735         else if (p->subs[2].owner == ast)
736                 res = 2;
737         else {
738                 res = -1;
739                 if (!nullok)
740                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
741         }
742         return res;
743 }
744
745 #ifdef ZAPATA_PRI
746 static void wakeup_sub(struct zt_pvt *p, int a, struct zt_pri *pri)
747 #else
748 static void wakeup_sub(struct zt_pvt *p, int a, void *pri)
749 #endif
750 {
751         struct ast_frame null = { AST_FRAME_NULL, };
752 #ifdef ZAPATA_PRI
753         if (pri)
754                 ast_mutex_unlock(&pri->lock);
755 #endif                  
756         for (;;) {
757                 if (p->subs[a].owner) {
758                         if (ast_mutex_trylock(&p->subs[a].owner->lock)) {
759                                 ast_mutex_unlock(&p->lock);
760                                 usleep(1);
761                                 ast_mutex_lock(&p->lock);
762                         } else {
763                                 ast_queue_frame(p->subs[a].owner, &null);
764                                 ast_mutex_unlock(&p->subs[a].owner->lock);
765                                 break;
766                         }
767                 } else
768                         break;
769         }
770 #ifdef ZAPATA_PRI
771         if (pri)
772                 ast_mutex_lock(&pri->lock);
773 #endif                  
774 }
775
776 #ifdef ZAPATA_PRI
777 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, struct zt_pri *pri)
778 #else
779 static void zap_queue_frame(struct zt_pvt *p, struct ast_frame *f, void *pri)
780 #endif
781 {
782         /* We must unlock the PRI to avoid the possibility of a deadlock */
783 #ifdef ZAPATA_PRI
784         if (pri)
785                 ast_mutex_unlock(&pri->lock);
786 #endif          
787         for (;;) {
788                 if (p->owner) {
789                         if (ast_mutex_trylock(&p->owner->lock)) {
790                                 ast_mutex_unlock(&p->lock);
791                                 usleep(1);
792                                 ast_mutex_lock(&p->lock);
793                         } else {
794                                 ast_queue_frame(p->owner, f);
795                                 ast_mutex_unlock(&p->owner->lock);
796                                 break;
797                         }
798                 } else
799                         break;
800         }
801 #ifdef ZAPATA_PRI
802         if (pri)
803                 ast_mutex_lock(&pri->lock);
804 #endif          
805 }
806
807 static int restore_gains(struct zt_pvt *p);
808
809 static void swap_subs(struct zt_pvt *p, int a, int b)
810 {
811         int tchan;
812         int tinthreeway;
813         struct ast_channel *towner;
814
815         ast_log(LOG_DEBUG, "Swapping %d and %d\n", a, b);
816
817         tchan = p->subs[a].chan;
818         towner = p->subs[a].owner;
819         tinthreeway = p->subs[a].inthreeway;
820
821         p->subs[a].chan = p->subs[b].chan;
822         p->subs[a].owner = p->subs[b].owner;
823         p->subs[a].inthreeway = p->subs[b].inthreeway;
824
825         p->subs[b].chan = tchan;
826         p->subs[b].owner = towner;
827         p->subs[b].inthreeway = tinthreeway;
828
829         if (p->subs[a].owner) 
830                 p->subs[a].owner->fds[0] = p->subs[a].zfd;
831         if (p->subs[b].owner) 
832                 p->subs[b].owner->fds[0] = p->subs[b].zfd;
833         wakeup_sub(p, a, NULL);
834         wakeup_sub(p, b, NULL);
835 }
836
837 static int zt_open(char *fn)
838 {
839         int fd;
840         int isnum;
841         int chan = 0;
842         int bs;
843         int x;
844         isnum = 1;
845         for (x=0;x<strlen(fn);x++) {
846                 if (!isdigit(fn[x])) {
847                         isnum = 0;
848                         break;
849                 }
850         }
851         if (isnum) {
852                 chan = atoi(fn);
853                 if (chan < 1) {
854                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
855                         return -1;
856                 }
857                 fn = "/dev/zap/channel";
858         }
859         fd = open(fn, O_RDWR | O_NONBLOCK);
860         if (fd < 0) {
861                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
862                 return -1;
863         }
864         if (chan) {
865                 if (ioctl(fd, ZT_SPECIFY, &chan)) {
866                         x = errno;
867                         close(fd);
868                         errno = x;
869                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
870                         return -1;
871                 }
872         }
873         bs = READ_SIZE;
874         if (ioctl(fd, ZT_SET_BLOCKSIZE, &bs) == -1) return -1;
875         return fd;
876 }
877
878 static void zt_close(int fd)
879 {
880         if(fd > 0)
881                 close(fd);
882 }
883
884 int zt_setlinear(int zfd, int linear)
885 {
886         int res;
887         res = ioctl(zfd, ZT_SETLINEAR, &linear);
888         if (res)
889                 return res;
890         return 0;
891 }
892
893
894 int zt_setlaw(int zfd, int law)
895 {
896         int res;
897         res = ioctl(zfd, ZT_SETLAW, &law);
898         if (res)
899                 return res;
900         return 0;
901 }
902
903 static int alloc_sub(struct zt_pvt *p, int x)
904 {
905         ZT_BUFFERINFO bi;
906         int res;
907         if (p->subs[x].zfd < 0) {
908                 p->subs[x].zfd = zt_open("/dev/zap/pseudo");
909                 if (p->subs[x].zfd > -1) {
910                         res = ioctl(p->subs[x].zfd, ZT_GET_BUFINFO, &bi);
911                         if (!res) {
912                                 bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
913                                 bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
914                                 bi.numbufs = numbufs;
915                                 res = ioctl(p->subs[x].zfd, ZT_SET_BUFINFO, &bi);
916                                 if (res < 0) {
917                                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
918                                 }
919                         } else 
920                                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
921                         if (ioctl(p->subs[x].zfd, ZT_CHANNO, &p->subs[x].chan) == 1) {
922                                 ast_log(LOG_WARNING,"Unable to get channel number for pseudo channel on FD %d\n",p->subs[x].zfd);
923                                 zt_close(p->subs[x].zfd);
924                                 p->subs[x].zfd = -1;
925                                 return -1;
926                         }
927                         if (option_debug)
928                                 ast_log(LOG_DEBUG, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
929                         return 0;
930                 } else
931                         ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
932                 return -1;
933         }
934         ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
935         return -1;
936 }
937
938 static int unalloc_sub(struct zt_pvt *p, int x)
939 {
940         if (!x) {
941                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
942                 return -1;
943         }
944         ast_log(LOG_DEBUG, "Released sub %d of channel %d\n", x, p->channel);
945         if (p->subs[x].zfd > -1) {
946                 zt_close(p->subs[x].zfd);
947         }
948         p->subs[x].zfd = -1;
949         p->subs[x].linear = 0;
950         p->subs[x].chan = 0;
951         p->subs[x].owner = NULL;
952         p->subs[x].inthreeway = 0;
953         p->polarity = POLARITY_IDLE;
954         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
955         return 0;
956 }
957
958 static int zt_digit(struct ast_channel *ast, char digit)
959 {
960         ZT_DIAL_OPERATION zo;
961         struct zt_pvt *p;
962         int res = 0;
963         int index;
964         p = ast->tech_pvt;
965         ast_mutex_lock(&p->lock);
966         index = zt_get_index(ast, p, 0);
967         if ((index == SUB_REAL) && p->owner) {
968 #ifdef ZAPATA_PRI
969                 if (p->sig == SIG_PRI && ast->_state == AST_STATE_DIALING && (p->proceeding < 2)) {
970                         if (p->setup_ack) {
971                                 if (!pri_grab(p, p->pri)) {
972                                         pri_information(p->pri->pri,p->call,digit);
973                                         pri_rel(p->pri);
974                                 } else
975                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
976                         } else if (strlen(p->dialdest) < sizeof(p->dialdest) - 1) {
977                                 ast_log(LOG_DEBUG, "Queueing digit '%c' since setup_ack not yet received\n", digit);
978                                 res = strlen(p->dialdest);
979                                 p->dialdest[res++] = digit;
980                                 p->dialdest[res] = '\0';
981                         }
982                 } else {
983 #else
984                 {
985 #endif
986                         zo.op = ZT_DIAL_OP_APPEND;
987                         zo.dialstr[0] = 'T';
988                         zo.dialstr[1] = digit;
989                         zo.dialstr[2] = 0;
990                         if ((res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &zo)))
991                                 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
992                         else
993                                 p->dialing = 1;
994                 }
995         }
996         ast_mutex_unlock(&p->lock);
997         return res;
998 }
999
1000 static char *events[] = {
1001                 "No event",
1002                 "On hook",
1003                 "Ring/Answered",
1004                 "Wink/Flash",
1005                 "Alarm",
1006                 "No more alarm",
1007                 "HDLC Abort",
1008                 "HDLC Overrun",
1009                 "HDLC Bad FCS",
1010                 "Dial Complete",
1011                 "Ringer On",
1012                 "Ringer Off",
1013                 "Hook Transition Complete",
1014                 "Bits Changed",
1015                 "Pulse Start",
1016                 "Timer Expired",
1017                 "Timer Ping",
1018                 "Polarity Reversal"
1019 };
1020
1021 static struct {
1022         int alarm;
1023         char *name;
1024 } alarms[] = {
1025         { ZT_ALARM_RED, "Red Alarm" },
1026         { ZT_ALARM_YELLOW, "Yellow Alarm" },
1027         { ZT_ALARM_BLUE, "Blue Alarm" },
1028         { ZT_ALARM_RECOVER, "Recovering" },
1029         { ZT_ALARM_LOOPBACK, "Loopback" },
1030         { ZT_ALARM_NOTOPEN, "Not Open" },
1031         { ZT_ALARM_NONE, "None" },
1032 };
1033
1034 static char *alarm2str(int alarm)
1035 {
1036         int x;
1037         for (x=0;x<sizeof(alarms) / sizeof(alarms[0]); x++) {
1038                 if (alarms[x].alarm & alarm)
1039                         return alarms[x].name;
1040         }
1041         return alarm ? "Unknown Alarm" : "No Alarm";
1042 }
1043
1044 static char *event2str(int event)
1045 {
1046         static char buf[256];
1047         if ((event < 18) && (event > -1))
1048                 return events[event];
1049         sprintf(buf, "Event %d", event); /* safe */
1050         return buf;
1051 }
1052
1053 #ifdef ZAPATA_PRI
1054 static char *dialplan2str(int dialplan)
1055 {
1056         if (dialplan == -1) {
1057                 return("Dynamically set dialplan in ISDN");
1058         }
1059         return(pri_plan2str(dialplan));
1060 }
1061 #endif
1062
1063 #ifdef ZAPATA_R2
1064 static int str2r2prot(char *swtype)
1065 {
1066     if (!strcasecmp(swtype, "ar"))
1067         return MFCR2_PROT_ARGENTINA;
1068     /*endif*/
1069     if (!strcasecmp(swtype, "cn"))
1070         return MFCR2_PROT_CHINA;
1071     /*endif*/
1072     if (!strcasecmp(swtype, "kr"))
1073         return MFCR2_PROT_KOREA;
1074     /*endif*/
1075     return -1;
1076 }
1077 #endif
1078
1079 static char *zap_sig2str(int sig)
1080 {
1081         static char buf[256];
1082         switch(sig) {
1083         case SIG_EM:
1084                 return "E & M Immediate";
1085         case SIG_EMWINK:
1086                 return "E & M Wink";
1087         case SIG_EM_E1:
1088                 return "E & M E1";
1089         case SIG_FEATD:
1090                 return "Feature Group D (DTMF)";
1091         case SIG_FEATDMF:
1092                 return "Feature Group D (MF)";
1093         case SIG_FEATDMF_TA:
1094                 return "Feature Groud D (MF) Tandem Access";
1095         case SIG_FEATB:
1096                 return "Feature Group B (MF)";
1097         case SIG_E911:
1098                 return "E911 (MF)";
1099         case SIG_FXSLS:
1100                 return "FXS Loopstart";
1101         case SIG_FXSGS:
1102                 return "FXS Groundstart";
1103         case SIG_FXSKS:
1104                 return "FXS Kewlstart";
1105         case SIG_FXOLS:
1106                 return "FXO Loopstart";
1107         case SIG_FXOGS:
1108                 return "FXO Groundstart";
1109         case SIG_FXOKS:
1110                 return "FXO Kewlstart";
1111         case SIG_PRI:
1112                 return "PRI Signalling";
1113         case SIG_R2:
1114                 return "R2 Signalling";
1115         case SIG_SF:
1116                 return "SF (Tone) Signalling Immediate";
1117         case SIG_SFWINK:
1118                 return "SF (Tone) Signalling Wink";
1119         case SIG_SF_FEATD:
1120                 return "SF (Tone) Signalling with Feature Group D (DTMF)";
1121         case SIG_SF_FEATDMF:
1122                 return "SF (Tone) Signalling with Feature Group D (MF)";
1123         case SIG_SF_FEATB:
1124                 return "SF (Tone) Signalling with Feature Group B (MF)";
1125         case SIG_GR303FXOKS:
1126                 return "GR-303 Signalling with FXOKS";
1127         case SIG_GR303FXSKS:
1128                 return "GR-303 Signalling with FXSKS";
1129         case 0:
1130                 return "Pseudo Signalling";
1131         default:
1132                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1133                 return buf;
1134         }
1135 }
1136
1137 #define sig2str zap_sig2str
1138
1139 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1140 {
1141         /* If the conference already exists, and we're already in it
1142            don't bother doing anything */
1143         ZT_CONFINFO zi;
1144         
1145         memset(&zi, 0, sizeof(zi));
1146         zi.chan = 0;
1147
1148         if (slavechannel > 0) {
1149                 /* If we have only one slave, do a digital mon */
1150                 zi.confmode = ZT_CONF_DIGITALMON;
1151                 zi.confno = slavechannel;
1152         } else {
1153                 if (!index) {
1154                         /* Real-side and pseudo-side both participate in conference */
1155                         zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1156                                                                 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1157                 } else
1158                         zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1159                 zi.confno = p->confno;
1160         }
1161         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1162                 return 0;
1163         if (c->zfd < 0)
1164                 return 0;
1165         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1166                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1167                 return -1;
1168         }
1169         if (slavechannel < 1) {
1170                 p->confno = zi.confno;
1171         }
1172         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1173         ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1174         return 0;
1175 }
1176
1177 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1178 {
1179         /* If they're listening to our channel, they're ours */ 
1180         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1181                 return 1;
1182         /* If they're a talker on our (allocated) conference, they're ours */
1183         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1184                 return 1;
1185         return 0;
1186 }
1187
1188 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1189 {
1190         ZT_CONFINFO zi;
1191         if (/* Can't delete if there's no zfd */
1192                 (c->zfd < 0) ||
1193                 /* Don't delete from the conference if it's not our conference */
1194                 !isourconf(p, c)
1195                 /* Don't delete if we don't think it's conferenced at all (implied) */
1196                 ) return 0;
1197         memset(&zi, 0, sizeof(zi));
1198         zi.chan = 0;
1199         zi.confno = 0;
1200         zi.confmode = 0;
1201         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1202                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1203                 return -1;
1204         }
1205         ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1206         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1207         return 0;
1208 }
1209
1210 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1211 {
1212         int x;
1213         int useslavenative;
1214         struct zt_pvt *slave = NULL;
1215         /* Start out optimistic */
1216         useslavenative = 1;
1217         /* Update conference state in a stateless fashion */
1218         for (x=0;x<3;x++) {
1219                 /* Any three-way calling makes slave native mode *definitely* out
1220                    of the question */
1221                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1222                         useslavenative = 0;
1223         }
1224         /* If we don't have any 3-way calls, check to see if we have
1225            precisely one slave */
1226         if (useslavenative) {
1227                 for (x=0;x<MAX_SLAVES;x++) {
1228                         if (p->slaves[x]) {
1229                                 if (slave) {
1230                                         /* Whoops already have a slave!  No 
1231                                            slave native and stop right away */
1232                                         slave = NULL;
1233                                         useslavenative = 0;
1234                                         break;
1235                                 } else {
1236                                         /* We have one slave so far */
1237                                         slave = p->slaves[x];
1238                                 }
1239                         }
1240                 }
1241         }
1242         /* If no slave, slave native definitely out */
1243         if (!slave)
1244                 useslavenative = 0;
1245         else if (slave->law != p->law) {
1246                 useslavenative = 0;
1247                 slave = NULL;
1248         }
1249         if (out)
1250                 *out = slave;
1251         return useslavenative;
1252 }
1253
1254 static int reset_conf(struct zt_pvt *p)
1255 {
1256         ZT_CONFINFO zi;
1257         memset(&zi, 0, sizeof(zi));
1258         p->confno = -1;
1259         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1260         if (p->subs[SUB_REAL].zfd > -1) {
1261                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1262                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1263         }
1264         return 0;
1265 }
1266
1267 static int update_conf(struct zt_pvt *p)
1268 {
1269         int needconf = 0;
1270         int x;
1271         int useslavenative;
1272         struct zt_pvt *slave = NULL;
1273
1274         useslavenative = isslavenative(p, &slave);
1275         /* Start with the obvious, general stuff */
1276         for (x=0;x<3;x++) {
1277                 /* Look for three way calls */
1278                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1279                         conf_add(p, &p->subs[x], x, 0);
1280                         needconf++;
1281                 } else {
1282                         conf_del(p, &p->subs[x], x);
1283                 }
1284         }
1285         /* If we have a slave, add him to our conference now. or DAX
1286            if this is slave native */
1287         for (x=0;x<MAX_SLAVES;x++) {
1288                 if (p->slaves[x]) {
1289                         if (useslavenative)
1290                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1291                         else {
1292                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1293                                 needconf++;
1294                         }
1295                 }
1296         }
1297         /* If we're supposed to be in there, do so now */
1298         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1299                 if (useslavenative)
1300                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1301                 else {
1302                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1303                         needconf++;
1304                 }
1305         }
1306         /* If we have a master, add ourselves to his conference */
1307         if (p->master) {
1308                 if (isslavenative(p->master, NULL)) {
1309                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1310                 } else {
1311                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1312                 }
1313         }
1314         if (!needconf) {
1315                 /* Nobody is left (or should be left) in our conference.  
1316                    Kill it.  */
1317                 p->confno = -1;
1318         }
1319         ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1320         return 0;
1321 }
1322
1323 static void zt_enable_ec(struct zt_pvt *p)
1324 {
1325         int x;
1326         int res;
1327         if (!p)
1328                 return;
1329         if (p->echocanon) {
1330                 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1331                 return;
1332         }
1333         if (p->digital) {
1334                 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1335                 return;
1336         }
1337         if (p->echocancel) {
1338                 if (p->sig == SIG_PRI) {
1339                         x = 1;
1340                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1341                         if (res)
1342                                 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1343                 }
1344                 x = p->echocancel;
1345                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1346                 if (res) 
1347                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1348                 else {
1349                         p->echocanon = 1;
1350                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1351                 }
1352         } else
1353                 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1354 }
1355
1356 static void zt_train_ec(struct zt_pvt *p)
1357 {
1358         int x;
1359         int res;
1360         if (p && p->echocancel && p->echotraining) {
1361                 x = p->echotraining;
1362                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1363                 if (res) 
1364                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1365                 else {
1366                         ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1367                 }
1368         } else
1369                 ast_log(LOG_DEBUG, "No echo training requested\n");
1370 }
1371
1372 static void zt_disable_ec(struct zt_pvt *p)
1373 {
1374         int x;
1375         int res;
1376         if (p->echocancel) {
1377                 x = 0;
1378                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1379                 if (res) 
1380                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1381                 else
1382                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1383         }
1384         p->echocanon = 0;
1385 }
1386
1387 int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1388 {
1389         struct  zt_gains g;
1390         float ltxgain;
1391         float lrxgain;
1392         int j,k;
1393         g.chan = chan;
1394         if ((rxgain != 0.0)  || (txgain != 0.0)) {
1395                 /* caluculate linear value of tx gain */
1396                 ltxgain = pow(10.0,txgain / 20.0);
1397                 /* caluculate linear value of rx gain */
1398                 lrxgain = pow(10.0,rxgain / 20.0);
1399                 if (law == ZT_LAW_ALAW) {
1400                         for (j=0;j<256;j++) {
1401                                 k = (int)(((float)AST_ALAW(j)) * lrxgain);
1402                                 if (k > 32767) k = 32767;
1403                                 if (k < -32767) k = -32767;
1404                                 g.rxgain[j] = AST_LIN2A(k);
1405                                 k = (int)(((float)AST_ALAW(j)) * ltxgain);
1406                                 if (k > 32767) k = 32767;
1407                                 if (k < -32767) k = -32767;
1408                                 g.txgain[j] = AST_LIN2A(k);
1409                         }
1410                 } else {
1411                         for (j=0;j<256;j++) {
1412                                 k = (int)(((float)AST_MULAW(j)) * lrxgain);
1413                                 if (k > 32767) k = 32767;
1414                                 if (k < -32767) k = -32767;
1415                                 g.rxgain[j] = AST_LIN2MU(k);
1416                                 k = (int)(((float)AST_MULAW(j)) * ltxgain);
1417                                 if (k > 32767) k = 32767;
1418                                 if (k < -32767) k = -32767;
1419                                 g.txgain[j] = AST_LIN2MU(k);
1420                         }
1421                 }
1422         } else {
1423                 for (j=0;j<256;j++) {
1424                         g.rxgain[j] = j;
1425                         g.txgain[j] = j;
1426                 }
1427         }
1428                 
1429           /* set 'em */
1430         return(ioctl(fd,ZT_SETGAINS,&g));
1431 }
1432
1433 static inline int zt_set_hook(int fd, int hs)
1434 {
1435         int x, res;
1436         x = hs;
1437         res = ioctl(fd, ZT_HOOK, &x);
1438         if (res < 0) 
1439         {
1440                 if (errno == EINPROGRESS) return 0;
1441                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1442         }
1443         return res;
1444 }
1445
1446 static inline int zt_confmute(struct zt_pvt *p, int muted)
1447 {
1448         int x, y, res;
1449         x = muted;
1450         if (p->sig == SIG_PRI) {
1451                 y = 1;
1452                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1453                 if (res)
1454                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1455         }
1456         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1457         if (res < 0) 
1458                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1459         return res;
1460 }
1461
1462 static int save_conference(struct zt_pvt *p)
1463 {
1464         struct zt_confinfo c;
1465         int res;
1466         if (p->saveconf.confmode) {
1467                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1468                 return -1;
1469         }
1470         p->saveconf.chan = 0;
1471         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1472         if (res) {
1473                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1474                 p->saveconf.confmode = 0;
1475                 return -1;
1476         }
1477         c.chan = 0;
1478         c.confno = 0;
1479         c.confmode = ZT_CONF_NORMAL;
1480         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1481         if (res) {
1482                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1483                 return -1;
1484         }
1485         if (option_debug)
1486                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1487         return 0;
1488 }
1489
1490 static int restore_conference(struct zt_pvt *p)
1491 {
1492         int res;
1493         if (p->saveconf.confmode) {
1494                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1495                 p->saveconf.confmode = 0;
1496                 if (res) {
1497                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1498                         return -1;
1499                 }
1500         }
1501         if (option_debug)
1502                 ast_log(LOG_DEBUG, "Restored conferencing\n");
1503         return 0;
1504 }
1505
1506 static int send_callerid(struct zt_pvt *p);
1507
1508 int send_cwcidspill(struct zt_pvt *p)
1509 {
1510         p->callwaitcas = 0;
1511         p->cidcwexpire = 0;
1512         p->cidspill = malloc(MAX_CALLERID_SIZE);
1513         if (p->cidspill) {
1514                 memset(p->cidspill, 0x7f, MAX_CALLERID_SIZE);
1515                 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1516                 /* Make sure we account for the end */
1517                 p->cidlen += READ_SIZE * 4;
1518                 p->cidpos = 0;
1519                 send_callerid(p);
1520                 if (option_verbose > 2)
1521                         ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1522         } else return -1;
1523         return 0;
1524 }
1525
1526 static int has_voicemail(struct zt_pvt *p)
1527 {
1528
1529         return ast_app_has_voicemail(p->mailbox, NULL);
1530 }
1531
1532 static int send_callerid(struct zt_pvt *p)
1533 {
1534         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1535         int res;
1536         /* Take out of linear mode if necessary */
1537         if (p->subs[SUB_REAL].linear) {
1538                 p->subs[SUB_REAL].linear = 0;
1539                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1540         }
1541         while(p->cidpos < p->cidlen) {
1542                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1543                 if (res < 0) {
1544                         if (errno == EAGAIN)
1545                                 return 0;
1546                         else {
1547                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1548                                 return -1;
1549                         }
1550                 }
1551                 if (!res)
1552                         return 0;
1553                 p->cidpos += res;
1554         }
1555         free(p->cidspill);
1556         p->cidspill = NULL;
1557         if (p->callwaitcas) {
1558                 /* Wait for CID/CW to expire */
1559                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1560         } else
1561                 restore_conference(p);
1562         return 0;
1563 }
1564
1565 static int zt_callwait(struct ast_channel *ast)
1566 {
1567         struct zt_pvt *p = ast->tech_pvt;
1568         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1569         if (p->cidspill) {
1570                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1571                 free(p->cidspill);
1572         }
1573         p->cidspill = malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4);
1574         if (p->cidspill) {
1575                 save_conference(p);
1576                 /* Silence */
1577                 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1578                 if (!p->callwaitrings && p->callwaitingcallerid) {
1579                         ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1580                         p->callwaitcas = 1;
1581                         p->cidlen = 2400 + 680 + READ_SIZE * 4;
1582                 } else {
1583                         ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1584                         p->callwaitcas = 0;
1585                         p->cidlen = 2400 + READ_SIZE * 4;
1586                 }
1587                 p->cidpos = 0;
1588                 send_callerid(p);
1589         } else {
1590                 ast_log(LOG_WARNING, "Unable to create SAS/CAS spill\n");
1591                 return -1;
1592         }
1593         return 0;
1594 }
1595
1596 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1597 {
1598         struct zt_pvt *p = ast->tech_pvt;
1599         int x, res, index;
1600         char *c, *n, *l;
1601 #ifdef ZAPATA_PRI
1602         char *s=NULL;
1603 #endif
1604         char dest[256]; /* must be same length as p->dialdest */
1605         ast_mutex_lock(&p->lock);
1606         ast_copy_string(dest, rdest, sizeof(dest));
1607         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
1608         if ((ast->_state == AST_STATE_BUSY)) {
1609                 p->subs[SUB_REAL].needbusy = 1;
1610                 ast_mutex_unlock(&p->lock);
1611                 return 0;
1612         }
1613         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1614                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1615                 ast_mutex_unlock(&p->lock);
1616                 return -1;
1617         }
1618         p->dialednone = 0;
1619         if (p->radio)  /* if a radio channel, up immediately */
1620         {
1621                 /* Special pseudo -- automatically up */
1622                 ast_setstate(ast, AST_STATE_UP); 
1623                 ast_mutex_unlock(&p->lock);
1624                 return 0;
1625         }
1626         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1627         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1628         if (res)
1629                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1630         p->outgoing = 1;
1631
1632         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1633
1634         switch(p->sig) {
1635         case SIG_FXOLS:
1636         case SIG_FXOGS:
1637         case SIG_FXOKS:
1638                 if (p->owner == ast) {
1639                         /* Normal ring, on hook */
1640                         
1641                         /* Don't send audio while on hook, until the call is answered */
1642                         p->dialing = 1;
1643                         if (p->use_callerid) {
1644                                 /* Generate the Caller-ID spill if desired */
1645                                 if (p->cidspill) {
1646                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1647                                         free(p->cidspill);
1648                                 }
1649                                 p->cidspill = malloc(MAX_CALLERID_SIZE);
1650                                 p->callwaitcas = 0;
1651                                 if (p->cidspill) {
1652                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1653                                         p->cidpos = 0;
1654                                         send_callerid(p);
1655                                 } else
1656                                         ast_log(LOG_WARNING, "Unable to generate CallerID spill\n");
1657                         }
1658                         /* Choose proper cadence */
1659                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1660                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering-1]))
1661                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1662                                 p->cidrings = cidrings[p->distinctivering - 1];
1663                         } else {
1664                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1665                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1666                                 p->cidrings = p->sendcalleridafter;
1667                         }
1668
1669
1670                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1671                         c = strchr(dest, '/');
1672                         if (c)
1673                                 c++;
1674                         if (c && (strlen(c) < p->stripmsd)) {
1675                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1676                                 c = NULL;
1677                         }
1678                         if (c) {
1679                                 p->dop.op = ZT_DIAL_OP_REPLACE;
1680                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1681                                 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1682                         } else {
1683                                 p->dop.dialstr[0] = '\0';
1684                         }
1685                         x = ZT_RING;
1686                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1687                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1688                                 ast_mutex_unlock(&p->lock);
1689                                 return -1;
1690                         }
1691                         p->dialing = 1;
1692                 } else {
1693                         /* Call waiting call */
1694                         p->callwaitrings = 0;
1695                         if (ast->cid.cid_num)
1696                                 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
1697                         else
1698                                 p->callwait_num[0] = '\0';
1699                         if (ast->cid.cid_name)
1700                                 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
1701                         else
1702                                 p->callwait_name[0] = '\0';
1703                         /* Call waiting tone instead */
1704                         if (zt_callwait(ast)) {
1705                                 ast_mutex_unlock(&p->lock);
1706                                 return -1;
1707                         }
1708                         /* Make ring-back */
1709                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1710                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1711                                 
1712                 }
1713                 n = ast->cid.cid_name;
1714                 l = ast->cid.cid_num;
1715                 if (l)
1716                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
1717                 else
1718                         p->lastcid_num[0] = '\0';
1719                 if (n)
1720                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
1721                 else
1722                         p->lastcid_name[0] = '\0';
1723                 ast_setstate(ast, AST_STATE_RINGING);
1724                 index = zt_get_index(ast, p, 0);
1725                 if (index > -1) {
1726                         p->subs[index].needringing = 1;
1727                 }
1728                 break;
1729         case SIG_FXSLS:
1730         case SIG_FXSGS:
1731         case SIG_FXSKS:
1732         case SIG_EMWINK:
1733         case SIG_EM:
1734         case SIG_EM_E1:
1735         case SIG_FEATD:
1736         case SIG_FEATDMF:
1737         case SIG_E911:
1738         case SIG_FEATB:
1739         case SIG_SFWINK:
1740         case SIG_SF:
1741         case SIG_SF_FEATD:
1742         case SIG_SF_FEATDMF:
1743         case SIG_FEATDMF_TA:
1744         case SIG_SF_FEATB:
1745                 c = strchr(dest, '/');
1746                 if (c)
1747                         c++;
1748                 else
1749                         c = "";
1750                 if (strlen(c) < p->stripmsd) {
1751                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1752                         ast_mutex_unlock(&p->lock);
1753                         return -1;
1754                 }
1755 #ifdef ZAPATA_PRI
1756                 /* Start the trunk, if not GR-303 */
1757                 if (!p->pri) {
1758 #endif
1759                         x = ZT_START;
1760                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1761                         if (res < 0) {
1762                                 if (errno != EINPROGRESS) {
1763                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1764                                         ast_mutex_unlock(&p->lock);
1765                                         return -1;
1766                                 }
1767                         }
1768 #ifdef ZAPATA_PRI
1769                 }
1770 #endif
1771                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1772                 p->dop.op = ZT_DIAL_OP_REPLACE;
1773                 if (p->sig == SIG_FEATD) {
1774                         l = ast->cid.cid_num;
1775                         if (l) 
1776                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c + p->stripmsd);
1777                         else
1778                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c + p->stripmsd);
1779                 } else 
1780                 if (p->sig == SIG_FEATDMF) {
1781                         l = ast->cid.cid_num;
1782                         if (l) 
1783                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c + p->stripmsd);
1784                         else
1785                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c + p->stripmsd);
1786                 } else 
1787                 if (p->sig == SIG_FEATDMF_TA) {
1788                         char *cic = NULL, *ozz = NULL;
1789                         /* If you have to go through a Tandem Access point you need to use this */
1790                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
1791                         if (!ozz)
1792                                 ozz = defaultozz;
1793                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
1794                         if (!cic)
1795                                 cic = defaultcic;
1796                         if (!ozz || !cic) {
1797                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
1798                                 ast_mutex_unlock(&p->lock);
1799                                 return -1;
1800                         }
1801                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
1802                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c + p->stripmsd);
1803                         p->whichwink = 0;
1804                 } else
1805                 if (p->sig == SIG_E911) {
1806                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
1807                 } else
1808                 if (p->sig == SIG_FEATB) {
1809                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c + p->stripmsd);
1810                 } else 
1811                 if(p->pulse)
1812                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c + p->stripmsd);
1813                 else
1814                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c + p->stripmsd);
1815                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
1816                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1817                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1818                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1819                         p->echobreak = 1;
1820                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1821                 } else
1822                         p->echobreak = 0;
1823                 if (!res) {
1824                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1825                                 x = ZT_ONHOOK;
1826                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1827                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1828                                 ast_mutex_unlock(&p->lock);
1829                                 return -1;
1830                         }
1831                 } else
1832                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1833                 p->dialing = 1;
1834                 if (strlen(c + p->stripmsd) < 1) p->dialednone = 1;
1835                 ast_setstate(ast, AST_STATE_DIALING);
1836                 break;
1837         case 0:
1838                 /* Special pseudo -- automatically up*/
1839                 ast_setstate(ast, AST_STATE_UP);
1840                 break;          
1841         case SIG_PRI:
1842                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
1843                 p->dialdest[0] = '\0';
1844                 break;
1845         default:
1846                 ast_log(LOG_DEBUG, "not yet implemented\n");
1847                 ast_mutex_unlock(&p->lock);
1848                 return -1;
1849         }
1850 #ifdef ZAPATA_PRI
1851         if (p->pri) {
1852                 struct pri_sr *sr;
1853                 int pridialplan;
1854                 int dp_strip;
1855                 int prilocaldialplan;
1856                 int ldp_strip;
1857                 c = strchr(dest, '/');
1858                 if (c)
1859                         c++;
1860                 else
1861                         c = dest;
1862                 if (!p->hidecallerid) {
1863                         l = ast->cid.cid_num;
1864                         n = ast->cid.cid_name;
1865                 } else {
1866                         l = NULL;
1867                         n = NULL;
1868                 }
1869                 if (strlen(c) < p->stripmsd) {
1870                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1871                         ast_mutex_unlock(&p->lock);
1872                         return -1;
1873                 }
1874                 if (p->sig != SIG_FXSKS) {
1875                         p->dop.op = ZT_DIAL_OP_REPLACE;
1876                         s = strchr(c + p->stripmsd, 'w');
1877                         if (s) {
1878                                 if (strlen(s) > 1)
1879                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
1880                                 else
1881                                         p->dop.dialstr[0] = '\0';
1882                                 *s = '\0';
1883                                 s++;
1884                         } else {
1885                                 p->dop.dialstr[0] = '\0';
1886                         }
1887                 }
1888                 if (pri_grab(p, p->pri)) {
1889                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
1890                         ast_mutex_unlock(&p->lock);
1891                         return -1;
1892                 }
1893                 if (!(p->call = pri_new_call(p->pri->pri))) {
1894                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1895                         pri_rel(p->pri);
1896                         ast_mutex_unlock(&p->lock);
1897                         return -1;
1898                 }
1899                 if (!(sr = pri_sr_new())) {
1900                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
1901                         pri_rel(p->pri);
1902                         ast_mutex_unlock(&p->lock);
1903                 }
1904                 if (p->bearer || (p->sig == SIG_FXSKS)) {
1905                         if (p->bearer) {
1906                                 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);
1907                                 p->bearer->call = p->call;
1908                         } else
1909                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
1910                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
1911                 }
1912                 p->digital = IS_DIGITAL(ast->transfercapability);
1913                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), 
1914                                                                 p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1);
1915                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
1916                                         (p->digital ? -1 : 
1917                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
1918                 if (p->pri->facilityenable)
1919                         pri_facility_enable(p->pri->pri);
1920
1921                 if (option_verbose > 2)
1922                         ast_verbose(VERBOSE_PREFIX_3 "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
1923                 dp_strip = 0;
1924                 pridialplan = p->pri->dialplan - 1;
1925                 if (pridialplan == -2) { /* compute dynamically */
1926                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
1927                                 dp_strip = strlen(p->pri->internationalprefix);
1928                                 pridialplan = PRI_INTERNATIONAL_ISDN;
1929                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
1930                                 dp_strip = strlen(p->pri->nationalprefix);
1931                                 pridialplan = PRI_NATIONAL_ISDN;
1932                         } else {
1933                                 pridialplan = PRI_LOCAL_ISDN;
1934                         }
1935                 }
1936                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan,  (s && *s) ? 1 : 0);
1937
1938                 ldp_strip = 0;
1939                 prilocaldialplan = p->pri->localdialplan - 1;
1940                 if ((l != NULL) && (prilocaldialplan == -2)) { /* compute dynamically */
1941                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
1942                                 ldp_strip = strlen(p->pri->internationalprefix);
1943                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
1944                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
1945                                 ldp_strip = strlen(p->pri->nationalprefix);
1946                                 prilocaldialplan = PRI_NATIONAL_ISDN;
1947                         } else {
1948                                 prilocaldialplan = PRI_LOCAL_ISDN;
1949                         }
1950                 }
1951                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan, 
1952                                         l ? (p->use_callingpres ? ast->cid.cid_pres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN) : 
1953                                                  PRES_NUMBER_NOT_AVAILABLE);
1954                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
1955                 if (pri_setup(p->pri->pri, p->call,  sr)) {
1956                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
1957                                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
1958                         pri_rel(p->pri);
1959                         ast_mutex_unlock(&p->lock);
1960                         pri_sr_free(sr);
1961                         return -1;
1962                 }
1963                 pri_sr_free(sr);
1964                 ast_setstate(ast, AST_STATE_DIALING);
1965                 pri_rel(p->pri);
1966         }
1967 #endif          
1968         ast_mutex_unlock(&p->lock);
1969         return 0;
1970 }
1971
1972 static void destroy_zt_pvt(struct zt_pvt **pvt)
1973 {
1974         struct zt_pvt *p = *pvt;
1975         /* Remove channel from the list */
1976         if(p->prev)
1977                 p->prev->next = p->next;
1978         if(p->next)
1979                 p->next->prev = p->prev;
1980         ast_mutex_destroy(&p->lock);
1981         free(p);
1982         *pvt = NULL;
1983 }
1984
1985 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1986 {
1987         int owned = 0;
1988         int i = 0;
1989
1990         if (!now) {
1991                 if (cur->owner) {
1992                         owned = 1;
1993                 }
1994
1995                 for (i = 0; i < 3; i++) {
1996                         if (cur->subs[i].owner) {
1997                                 owned = 1;
1998                         }
1999                 }
2000                 if (!owned) {
2001                         if (prev) {
2002                                 prev->next = cur->next;
2003                                 if (prev->next)
2004                                         prev->next->prev = prev;
2005                                 else
2006                                         ifend = prev;
2007                         } else {
2008                                 iflist = cur->next;
2009                                 if (iflist)
2010                                         iflist->prev = NULL;
2011                                 else
2012                                         ifend = NULL;
2013                         }
2014                         if (cur->subs[SUB_REAL].zfd > -1) {
2015                                 zt_close(cur->subs[SUB_REAL].zfd);
2016                         }
2017                         destroy_zt_pvt(&cur);
2018                 }
2019         } else {
2020                 if (prev) {
2021                         prev->next = cur->next;
2022                         if (prev->next)
2023                                 prev->next->prev = prev;
2024                         else
2025                                 ifend = prev;
2026                 } else {
2027                         iflist = cur->next;
2028                         if (iflist)
2029                                 iflist->prev = NULL;
2030                         else
2031                                 ifend = NULL;
2032                 }
2033                 if (cur->subs[SUB_REAL].zfd > -1) {
2034                         zt_close(cur->subs[SUB_REAL].zfd);
2035                 }
2036                 destroy_zt_pvt(&cur);
2037         }
2038         return 0;
2039 }
2040
2041 #ifdef ZAPATA_PRI
2042 int pri_is_up(struct zt_pri *pri)
2043 {
2044         int x;
2045         for (x=0;x<NUM_DCHANS;x++) {
2046                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2047                         return 1;
2048         }
2049         return 0;
2050 }
2051
2052 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
2053 {
2054         bearer->owner = &inuse;
2055         bearer->realcall = crv;
2056         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2057         if (crv->subs[SUB_REAL].owner)
2058                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
2059         crv->bearer = bearer;
2060         crv->call = bearer->call;
2061         crv->pri = pri;
2062         return 0;
2063 }
2064
2065 static char *pri_order(int level)
2066 {
2067         switch(level) {
2068         case 0:
2069                 return "Primary";
2070         case 1:
2071                 return "Secondary";
2072         case 2:
2073                 return "Tertiary";
2074         case 3:
2075                 return "Quaternary";
2076         default:
2077                 return "<Unknown>";
2078         }               
2079 }
2080
2081 /* Returns fd of the active dchan */
2082 int pri_active_dchan_fd(struct zt_pri *pri)
2083 {
2084         int x = -1;
2085
2086         for (x = 0; x < NUM_DCHANS; x++)
2087                 if ((pri->dchans[x] == pri->pri))
2088                         break;
2089
2090         return pri->fds[x];
2091 }
2092
2093 int pri_find_dchan(struct zt_pri *pri)
2094 {
2095         int oldslot = -1;
2096         struct pri *old;
2097         int newslot = -1;
2098         int x;
2099         old = pri->pri;
2100         for(x=0;x<NUM_DCHANS;x++) {
2101                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2102                         newslot = x;
2103                 if (pri->dchans[x] == old) {
2104                         oldslot = x;
2105                 }
2106         }
2107         if (newslot < 0) {
2108                 newslot = 0;
2109                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary on channel anyway %d!\n",
2110                         pri->dchannels[newslot]);
2111         }
2112         if (old && (oldslot != newslot))
2113                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2114                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2115         pri->pri = pri->dchans[newslot];
2116         return 0;
2117 }
2118 #endif
2119
2120 static int zt_hangup(struct ast_channel *ast)
2121 {
2122         int res;
2123         int index,x, law;
2124         /*static int restore_gains(struct zt_pvt *p);*/
2125         struct zt_pvt *p = ast->tech_pvt;
2126         struct zt_pvt *tmp = NULL;
2127         struct zt_pvt *prev = NULL;
2128         ZT_PARAMS par;
2129
2130         if (option_debug)
2131                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
2132         if (!ast->tech_pvt) {
2133                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2134                 return 0;
2135         }
2136         
2137         ast_mutex_lock(&p->lock);
2138         
2139         index = zt_get_index(ast, p, 1);
2140
2141         if (p->sig == SIG_PRI) {
2142                 x = 1;
2143                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2144         }
2145
2146         x = 0;
2147         zt_confmute(p, 0);
2148         restore_gains(p);
2149         if (p->origcid_num) {
2150                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2151                 free(p->origcid_num);
2152                 p->origcid_num = NULL;
2153         }       
2154         if (p->origcid_name) {
2155                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2156                 free(p->origcid_name);
2157                 p->origcid_name = NULL;
2158         }       
2159         if (p->dsp)
2160                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2161         if (p->exten)
2162                 p->exten[0] = '\0';
2163
2164         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2165                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2166         p->ignoredtmf = 0;
2167         
2168         if (index > -1) {
2169                 /* Real channel, do some fixup */
2170                 p->subs[index].owner = NULL;
2171                 p->subs[index].needanswer = 0;
2172                 p->subs[index].needflash = 0;
2173                 p->subs[index].needringing = 0;
2174                 p->subs[index].needbusy = 0;
2175                 p->subs[index].needcongestion = 0;
2176                 p->subs[index].linear = 0;
2177                 p->subs[index].needcallerid = 0;
2178                 p->polarity = POLARITY_IDLE;
2179                 zt_setlinear(p->subs[index].zfd, 0);
2180                 if (index == SUB_REAL) {
2181                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2182                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2183                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2184                                         /* We had flipped over to answer a callwait and now it's gone */
2185                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2186                                         /* Move to the call-wait, but un-own us until they flip back. */
2187                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2188                                         unalloc_sub(p, SUB_CALLWAIT);
2189                                         p->owner = NULL;
2190                                 } else {
2191                                         /* The three way hung up, but we still have a call wait */
2192                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2193                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2194                                         unalloc_sub(p, SUB_THREEWAY);
2195                                         if (p->subs[SUB_REAL].inthreeway) {
2196                                                 /* This was part of a three way call.  Immediately make way for
2197                                                    another call */
2198                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2199                                                 p->owner = p->subs[SUB_REAL].owner;
2200                                         } else {
2201                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2202                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2203                                                 p->owner = NULL;
2204                                         }
2205                                         p->subs[SUB_REAL].inthreeway = 0;
2206                                 }
2207                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2208                                 /* Move to the call-wait and switch back to them. */
2209                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2210                                 unalloc_sub(p, SUB_CALLWAIT);
2211                                 p->owner = p->subs[SUB_REAL].owner;
2212                                 if (p->owner->_state != AST_STATE_UP)
2213                                         p->subs[SUB_REAL].needanswer = 1;
2214                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2215                                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
2216                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2217                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2218                                 unalloc_sub(p, SUB_THREEWAY);
2219                                 if (p->subs[SUB_REAL].inthreeway) {
2220                                         /* This was part of a three way call.  Immediately make way for
2221                                            another call */
2222                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2223                                         p->owner = p->subs[SUB_REAL].owner;
2224                                 } else {
2225                                         /* This call hasn't been completed yet...  Set owner to NULL */
2226                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2227                                         p->owner = NULL;
2228                                 }
2229                                 p->subs[SUB_REAL].inthreeway = 0;
2230                         }
2231                 } else if (index == SUB_CALLWAIT) {
2232                         /* Ditch the holding callwait call, and immediately make it availabe */
2233                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2234                                 /* This is actually part of a three way, placed on hold.  Place the third part
2235                                    on music on hold now */
2236                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2237                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
2238                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2239                                 /* Make it the call wait now */
2240                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2241                                 unalloc_sub(p, SUB_THREEWAY);
2242                         } else
2243                                 unalloc_sub(p, SUB_CALLWAIT);
2244                 } else if (index == SUB_THREEWAY) {
2245                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2246                                 /* The other party of the three way call is currently in a call-wait state.
2247                                    Start music on hold for them, and take the main guy out of the third call */
2248                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
2249                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
2250                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2251                         }
2252                         p->subs[SUB_REAL].inthreeway = 0;
2253                         /* If this was part of a three way call index, let us make
2254                            another three way call */
2255                         unalloc_sub(p, SUB_THREEWAY);
2256                 } else {
2257                         /* This wasn't any sort of call, but how are we an index? */
2258                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2259                 }
2260         }
2261
2262
2263         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2264                 p->owner = NULL;
2265                 p->ringt = 0;
2266                 p->distinctivering = 0;
2267                 p->confirmanswer = 0;
2268                 p->cidrings = 1;
2269                 p->outgoing = 0;
2270                 p->digital = 0;
2271                 p->faxhandled = 0;
2272                 p->pulsedial = 0;
2273                 p->onhooktime = time(NULL);
2274 #ifdef ZAPATA_PRI
2275                 p->proceeding = 0;
2276                 p->alerting = 0;
2277                 p->setup_ack = 0;
2278 #endif          
2279                 if (p->dsp) {
2280                         ast_dsp_free(p->dsp);
2281                         p->dsp = NULL;
2282                 }
2283
2284                 law = ZT_LAW_DEFAULT;
2285                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2286                 if (res < 0) 
2287                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2288                 /* Perform low level hangup if no owner left */
2289 #ifdef ZAPATA_PRI
2290                 if (p->pri) {
2291                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2292                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2293                                 if (!pri_grab(p, p->pri)) {
2294                                         if (p->alreadyhungup) {
2295                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2296                                                 pri_hangup(p->pri->pri, p->call, -1);
2297                                                 p->call = NULL;
2298                                                 if (p->bearer) 
2299                                                         p->bearer->call = NULL;
2300                                         } else {
2301                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2302                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2303                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2304                                                 p->alreadyhungup = 1;
2305                                                 if (p->bearer)
2306                                                         p->bearer->alreadyhungup = 1;
2307                                                 if (cause) {
2308                                                         if (atoi(cause))
2309                                                                 icause = atoi(cause);
2310                                                 }
2311                                                 pri_hangup(p->pri->pri, p->call, icause);
2312                                         }
2313                                         if (res < 0) 
2314                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2315                                         pri_rel(p->pri);                        
2316                                 } else {
2317                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2318                                         res = -1;
2319                                 }
2320                         } else {
2321                                 if (p->bearer)
2322                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2323                                 p->call = NULL;
2324                                 res = 0;
2325                         }
2326                 }
2327 #endif
2328 #ifdef ZAPATA_R2
2329                 if (p->sig == SIG_R2) {
2330                         if (p->hasr2call) {
2331                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2332                                 p->hasr2call = 0;
2333                                 res = 0;
2334                         } else
2335                                 res = 0;
2336
2337                 }
2338 #endif
2339                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2340                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2341                 if (res < 0) {
2342                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2343                 }
2344                 switch(p->sig) {
2345                 case SIG_FXOGS:
2346                 case SIG_FXOLS:
2347                 case SIG_FXOKS:
2348                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2349                         if (!res) {
2350 #if 0
2351                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2352 #endif
2353                                 /* If they're off hook, try playing congestion */
2354                                 if ((par.rxisoffhook) && (!p->radio))
2355                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2356                                 else
2357                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2358                         }
2359                         break;
2360                 case SIG_FXSGS:
2361                 case SIG_FXSLS:
2362                 case SIG_FXSKS:
2363                         /* Make sure we're not made available for at least two seconds assuming
2364                            we were actually used for an inbound or outbound call. */
2365                         if (ast->_state != AST_STATE_RESERVED) {
2366                                 time(&p->guardtime);
2367                                 p->guardtime += 2;
2368                         }
2369                         break;
2370                 default:
2371                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2372                 }
2373                 if (p->cidspill)
2374                         free(p->cidspill);
2375                 if (p->sig)
2376                         zt_disable_ec(p);
2377                 x = 0;
2378                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2379                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2380                 p->didtdd = 0;
2381                 p->cidspill = NULL;
2382                 p->callwaitcas = 0;
2383                 p->callwaiting = p->permcallwaiting;
2384                 p->hidecallerid = p->permhidecallerid;
2385                 p->dialing = 0;
2386                 p->rdnis[0] = '\0';
2387                 update_conf(p);
2388                 reset_conf(p);
2389                 /* Restore data mode */
2390                 if (p->sig == SIG_PRI) {
2391                         x = 0;
2392                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2393                 }
2394 #ifdef ZAPATA_PRI
2395                 if (p->bearer) {
2396                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2397                         /* Free up the bearer channel as well, and
2398                            don't use its file descriptor anymore */
2399                         update_conf(p->bearer);
2400                         reset_conf(p->bearer);
2401                         p->bearer->owner = NULL;
2402                         p->bearer->realcall = NULL;
2403                         p->bearer = NULL;
2404                         p->subs[SUB_REAL].zfd = -1;
2405                         p->pri = NULL;
2406                 }
2407 #endif
2408                 restart_monitor();
2409         }
2410
2411
2412         p->callwaitingrepeat = 0;
2413         p->cidcwexpire = 0;
2414         ast->tech_pvt = NULL;
2415         ast_mutex_unlock(&p->lock);
2416         ast_mutex_lock(&usecnt_lock);
2417         usecnt--;
2418         if (usecnt < 0) 
2419                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2420         ast_mutex_unlock(&usecnt_lock);
2421         ast_update_use_count();
2422         if (option_verbose > 2) 
2423                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2424
2425         ast_mutex_lock(&iflock);
2426         tmp = iflist;
2427         prev = NULL;
2428         if (p->destroy) {
2429                 while (tmp) {
2430                         if (tmp == p) {
2431                                 destroy_channel(prev, tmp, 0);
2432                                 break;
2433                         } else {
2434                                 prev = tmp;
2435                                 tmp = tmp->next;
2436                         }
2437                 }
2438         }
2439         ast_mutex_unlock(&iflock);
2440         return 0;
2441 }
2442
2443 static int zt_answer(struct ast_channel *ast)
2444 {
2445         struct zt_pvt *p = ast->tech_pvt;
2446         int res=0;
2447         int index;
2448         int oldstate = ast->_state;
2449         ast_setstate(ast, AST_STATE_UP);
2450         ast_mutex_lock(&p->lock);
2451         index = zt_get_index(ast, p, 0);
2452         if (index < 0)
2453                 index = SUB_REAL;
2454         /* nothing to do if a radio channel */
2455         if (p->radio) {
2456                 ast_mutex_unlock(&p->lock);
2457                 return 0;
2458         }
2459         switch(p->sig) {
2460         case SIG_FXSLS:
2461         case SIG_FXSGS:
2462         case SIG_FXSKS:
2463                 p->ringt = 0;
2464                 /* Fall through */
2465         case SIG_EM:
2466         case SIG_EM_E1:
2467         case SIG_EMWINK:
2468         case SIG_FEATD:
2469         case SIG_FEATDMF:
2470         case SIG_E911:
2471         case SIG_FEATB:
2472         case SIG_SF:
2473         case SIG_SFWINK:
2474         case SIG_SF_FEATD:
2475         case SIG_SF_FEATDMF:
2476         case SIG_SF_FEATB:
2477         case SIG_FXOLS:
2478         case SIG_FXOGS:
2479         case SIG_FXOKS:
2480                 /* Pick up the line */
2481                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2482                 if(p->hanguponpolarityswitch) {
2483                         gettimeofday(&p->polaritydelaytv, NULL);
2484                 }
2485                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2486                 tone_zone_play_tone(p->subs[index].zfd, -1);
2487                 p->dialing = 0;
2488                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2489                         if (oldstate == AST_STATE_RINGING) {
2490                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2491                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2492                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2493                                 p->owner = p->subs[SUB_REAL].owner;
2494                         }
2495                 }
2496                 if (p->sig & __ZT_SIG_FXS) {
2497                         zt_enable_ec(p);
2498                         zt_train_ec(p);
2499                 }
2500                 break;
2501 #ifdef ZAPATA_PRI
2502         case SIG_PRI:
2503                 /* Send a pri acknowledge */
2504                 if (!pri_grab(p, p->pri)) {
2505                         p->proceeding = 2;
2506                         res = pri_answer(p->pri->pri, p->call, 0, !p->digital);
2507                         pri_rel(p->pri);
2508                 } else {
2509                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2510                         res= -1;
2511                 }
2512                 break;
2513 #endif
2514 #ifdef ZAPATA_R2
2515         case SIG_R2:
2516                 res = mfcr2_AnswerCall(p->r2, NULL);
2517                 if (res)
2518                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2519                 break;
2520 #endif                  
2521         case 0:
2522                 ast_mutex_unlock(&p->lock);
2523                 return 0;
2524         default:
2525                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2526                 res = -1;
2527         }
2528         ast_mutex_unlock(&p->lock);
2529         return res;
2530 }
2531
2532 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2533 {
2534 char    *cp;
2535 int     x;
2536
2537         struct zt_pvt *p = chan->tech_pvt;
2538
2539         
2540         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2541                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2542            {
2543                 errno = ENOSYS;
2544                 return -1;
2545            }
2546         cp = (char *)data;
2547         if ((!cp) || (datalen < 1))
2548            {
2549                 errno = EINVAL;
2550                 return -1;
2551            }
2552         switch(option) {
2553             case AST_OPTION_TONE_VERIFY:
2554                 if (!p->dsp)
2555                         break;
2556                 switch(*cp) {
2557                     case 1:
2558                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2559                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2560                         break;
2561                     case 2:
2562                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2563                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2564                         break;
2565                     default:
2566                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2567                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2568                         break;
2569                 }
2570                 break;
2571             case AST_OPTION_TDD:  /* turn on or off TDD */
2572                 if (!*cp) { /* turn it off */
2573                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2574                         if (p->tdd) tdd_free(p->tdd);
2575                         p->tdd = 0;
2576                         p->mate = 0;
2577                         break;
2578                 }
2579                 if (*cp == 2)
2580                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2581                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2582                 p->mate = 0;
2583                 zt_disable_ec(p);
2584                 /* otherwise, turn it on */
2585                 if (!p->didtdd) { /* if havent done it yet */
2586                         unsigned char mybuf[41000],*buf;
2587                         int size,res,fd,len;
2588                         int index;
2589                         struct pollfd fds[1];
2590                         buf = mybuf;
2591                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2592                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2593                         len = 40000;
2594                         index = zt_get_index(chan, p, 0);
2595                         if (index < 0) {
2596                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2597                                 return -1;
2598                         }
2599                         fd = p->subs[index].zfd;
2600                         while(len) {
2601                                 if (ast_check_hangup(chan)) return -1;
2602                                 size = len;
2603                                 if (size > READ_SIZE)
2604                                         size = READ_SIZE;
2605                                 fds[0].fd = fd;
2606                                 fds[0].events = POLLPRI | POLLOUT;
2607                                 res = poll(fds, 1, -1);
2608                                 if (!res) {
2609                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2610                                         continue;
2611                                 }
2612                                   /* if got exception */
2613                                 if (fds[0].revents & POLLPRI) return -1;
2614                                 if (!(fds[0].revents & POLLOUT)) {
2615                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2616                                         continue;
2617                                 }
2618                                 res = write(fd, buf, size);
2619                                 if (res != size) {
2620                                         if (res == -1) return -1;
2621                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2622                                         break;
2623                                 }
2624                                 len -= size;
2625                                 buf += size;
2626                         }
2627                         p->didtdd = 1; /* set to have done it now */            
2628                 }
2629                 if (*cp == 2) { /* Mate mode */
2630                         if (p->tdd) tdd_free(p->tdd);
2631                         p->tdd = 0;
2632                         p->mate = 1;
2633                         break;
2634                         }               
2635                 if (!p->tdd) { /* if we dont have one yet */
2636                         p->tdd = tdd_new(); /* allocate one */
2637                 }               
2638                 break;
2639             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2640                 if (!*cp)
2641                 {               
2642                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2643                         x = 0;
2644                 }
2645                 else
2646                 {               
2647                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2648                         x = 1;
2649                 }
2650                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2651                 break;
2652             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2653                 if (!*cp)
2654                 {               
2655                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2656                         x = 0;
2657                         zt_disable_ec(p);
2658                 }
2659                 else
2660                 {               
2661                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2662                         x = 1;
2663                 }
2664                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2665                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2666                 break;
2667         }
2668         errno = 0;
2669         return 0;
2670 }
2671
2672 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2673 {
2674         /* Unlink a specific slave or all slaves/masters from a given master */
2675         int x;
2676         int hasslaves;
2677         if (!master)
2678                 return;
2679         if (needlock) {
2680                 ast_mutex_lock(&master->lock);
2681                 if (slave) {
2682                         while(ast_mutex_trylock(&slave->lock)) {
2683                                 ast_mutex_unlock(&master->lock);
2684                                 usleep(1);
2685                                 ast_mutex_lock(&master->lock);
2686                         }
2687                 }
2688         }
2689         hasslaves = 0;
2690         for (x=0;x<MAX_SLAVES;x++) {
2691                 if (master->slaves[x]) {
2692                         if (!slave || (master->slaves[x] == slave)) {
2693                                 /* Take slave out of the conference */
2694                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2695                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2696                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2697                                 master->slaves[x]->master = NULL;
2698                                 master->slaves[x] = NULL;
2699                         } else
2700                                 hasslaves = 1;
2701                 }
2702                 if (!hasslaves)
2703                         master->inconference = 0;
2704         }
2705         if (!slave) {
2706                 if (master->master) {
2707                         /* Take master out of the conference */
2708                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2709                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2710                         hasslaves = 0;
2711                         for (x=0;x<MAX_SLAVES;x++) {
2712                                 if (master->master->slaves[x] == master)
2713                                         master->master->slaves[x] = NULL;
2714                                 else if (master->master->slaves[x])
2715                                         hasslaves = 1;
2716                         }
2717                         if (!hasslaves)
2718                                 master->master->inconference = 0;
2719                 }
2720                 master->master = NULL;
2721         }
2722         update_conf(master);
2723         if (needlock) {
2724                 if (slave)
2725                         ast_mutex_unlock(&slave->lock);
2726                 ast_mutex_unlock(&master->lock);
2727         }
2728 }
2729
2730 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2731         int x;
2732         if (!slave || !master) {
2733                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2734                 return;
2735         }
2736         for (x=0;x<MAX_SLAVES;x++) {
2737                 if (!master->slaves[x]) {
2738                         master->slaves[x] = slave;
2739                         break;
2740                 }
2741         }
2742         if (x >= MAX_SLAVES) {
2743                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2744                 master->slaves[MAX_SLAVES - 1] = slave;
2745         }
2746         if (slave->master) 
2747                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2748         slave->master = master;
2749         
2750         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2751 }
2752
2753 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2754 {
2755         struct ast_channel *who = NULL, *cs[3];
2756         struct zt_pvt *p0, *p1, *op0, *op1;
2757         struct zt_pvt *master=NULL, *slave=NULL;
2758         struct ast_frame *f;
2759         int to;
2760         int inconf = 0;
2761         int nothingok = 0;
2762         int ofd1, ofd2;
2763         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2764         int os1 = -1, os2 = -1;
2765         struct ast_channel *oc1, *oc2;
2766 #ifdef PRI_2BCT
2767         int triedtopribridge = 0;
2768         q931_call *q931c0 = NULL, *q931c1 = NULL;
2769 #endif
2770
2771
2772         /* if need DTMF, cant native bridge */
2773         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2774                 return -2;
2775                 
2776         ast_mutex_lock(&c0->lock);
2777         ast_mutex_lock(&c1->lock);
2778
2779         p0 = c0->tech_pvt;
2780         p1 = c1->tech_pvt;
2781         /* cant do pseudo-channels here */
2782         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2783                 ast_mutex_unlock(&c0->lock);
2784                 ast_mutex_unlock(&c1->lock);
2785                 return -2;
2786         }
2787
2788         op0 = p0 = c0->tech_pvt;
2789         op1 = p1 = c1->tech_pvt;
2790         ofd1 = c0->fds[0];
2791         ofd2 = c1->fds[0];
2792         oi1 = zt_get_index(c0, p0, 0);
2793         oi2 = zt_get_index(c1, p1, 0);
2794         oc1 = p0->owner;
2795         oc2 = p1->owner;
2796         if ((oi1 < 0) || (oi2 < 0)) {
2797                 ast_mutex_unlock(&c0->lock);
2798                 ast_mutex_unlock(&c1->lock);
2799                 return -1;
2800         }
2801
2802
2803
2804         ast_mutex_lock(&p0->lock);
2805         if (ast_mutex_trylock(&p1->lock)) {
2806                 /* Don't block, due to potential for deadlock */
2807                 ast_mutex_unlock(&p0->lock);
2808                 ast_mutex_unlock(&c0->lock);
2809                 ast_mutex_unlock(&c1->lock);
2810                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2811                 return -3;
2812         }
2813         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2814                 if (!p0->owner || !p1->owner) {
2815                         /* Currently unowned -- Do nothing.  */
2816                         nothingok = 1;
2817                 } else {
2818                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2819                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2820                                 master = p0;
2821                                 slave = p1;
2822                                 inconf = 1;
2823                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2824                                 master = p1;
2825                                 slave = p0;
2826                                 inconf = 1;
2827                         } else {
2828                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2829                                 ast_log(LOG_WARNING, "p0: chan %d/%d/CW%d/3W%d, p1: chan %d/%d/CW%d/3W%d\n", p0->channel, oi1, (p0->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p0->subs[SUB_REAL].inthreeway,
2830                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2831                         }
2832                 }
2833         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2834                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2835                         master = p1;
2836                         slave = p0;
2837                 } else {
2838                         nothingok = 1;
2839                 }
2840         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2841                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2842                         master = p0;
2843                         slave = p1;
2844                 } else {
2845                         nothingok  = 1;
2846                 }
2847         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2848                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2849                    don't put us in anything */
2850                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2851                         master = p1;
2852                         slave = p0;
2853                 } else {
2854                         nothingok = 1;
2855                 }
2856         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2857                 /* Same as previous */
2858                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2859                         master = p0;
2860                         slave = p1;
2861                 } else {
2862                         nothingok = 1;
2863                 }
2864         }
2865         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2866                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2867         if (master && slave) {
2868                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2869                    in an active threeway call with a channel that is ringing, we should
2870                    indicate ringing. */
2871                 if ((oi2 == SUB_THREEWAY) && 
2872                         p1->subs[SUB_THREEWAY].inthreeway && 
2873                         p1->subs[SUB_REAL].owner && 
2874                         p1->subs[SUB_REAL].inthreeway && 
2875                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2876                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2877                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2878                                 os2 = p1->subs[SUB_REAL].owner->_state;
2879                 } else {
2880                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2881                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2882                 }
2883                 if ((oi1 == SUB_THREEWAY) && 
2884                         p0->subs[SUB_THREEWAY].inthreeway && 
2885                         p0->subs[SUB_REAL].owner && 
2886                         p0->subs[SUB_REAL].inthreeway && 
2887                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2888                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2889                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2890                                 os1 = p0->subs[SUB_REAL].owner->_state;
2891                 } else {
2892                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2893                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2894                 }
2895                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2896                         if (!p0->echocanbridged || !p1->echocanbridged) {
2897                                 /* Disable echo cancellation if appropriate */
2898                                 zt_disable_ec(p0);
2899                                 zt_disable_ec(p1);
2900                         }
2901                 }
2902                 zt_link(slave, master);
2903                 master->inconference = inconf;
2904         } else if (!nothingok)
2905                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2906
2907         update_conf(p0);
2908         update_conf(p1);
2909         t1 = p0->subs[SUB_REAL].inthreeway;
2910         t2 = p1->subs[SUB_REAL].inthreeway;
2911
2912         ast_mutex_unlock(&p0->lock);
2913         ast_mutex_unlock(&p1->lock);
2914
2915         ast_mutex_unlock(&c0->lock);
2916         ast_mutex_unlock(&c1->lock);
2917
2918         /* Native bridge failed */
2919         if ((!master || !slave) && !nothingok) {
2920                 if (op0 == p0)
2921                         zt_enable_ec(p0);
2922                 if (op1 == p1)
2923                         zt_enable_ec(p1);
2924                 return -1;
2925         }
2926         
2927         cs[0] = c0;
2928         cs[1] = c1;
2929         cs[2] = NULL;
2930         for (;;) {
2931                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2932                    and then balking if anything is wrong */
2933                 ast_mutex_lock(&c0->lock);
2934                 ast_mutex_lock(&c1->lock);
2935                 p0 = c0->tech_pvt;
2936                 p1 = c1->tech_pvt;
2937
2938 #ifdef PRI_2BCT
2939                 q931c0 = p0->call;
2940                 q931c1 = p1->call;
2941                 if (p0->transfer && p1->transfer 
2942                                 && q931c0 && q931c1 
2943                                 && !triedtopribridge) {
2944
2945                         pri_channel_bridge(q931c0, q931c1);
2946                         triedtopribridge = 1;
2947                 }
2948 #endif
2949                 if (op0 == p0)
2950                         i1 = zt_get_index(c0, p0, 1);
2951                 if (op1 == p1)
2952                         i2 = zt_get_index(c1, p1, 1);
2953                 ast_mutex_unlock(&c0->lock);
2954                 ast_mutex_unlock(&c1->lock);
2955                 if ((op0 != p0) || (op1 != p1) || 
2956                     (ofd1 != c0->fds[0]) || 
2957                         (ofd2 != c1->fds[0]) ||
2958                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2959                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2960                     (oc1 != p0->owner) || 
2961                         (oc2 != p1->owner) ||
2962                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2963                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2964                         (oi1 != i1) ||
2965                         (oi2 != i2)) {
2966                         if (slave && master)
2967                                 zt_unlink(slave, master, 1);
2968                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2969                                                                         op0->channel, oi1, op1->channel, oi2);
2970                         if (op0 == p0)
2971                                 zt_enable_ec(p0);
2972                         if (op1 == p1)
2973                                 zt_enable_ec(p1);
2974                         return -3;
2975                 }
2976                 to = -1;
2977                 who = ast_waitfor_n(cs, 2, &to);
2978                 if (!who) {
2979                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2980                         continue;
2981                 }
2982                 if (who->tech_pvt == op0) 
2983                         op0->ignoredtmf = 1;
2984                 else if (who->tech_pvt == op1)
2985                         op1->ignoredtmf = 1;
2986                 f = ast_read(who);
2987                 if (who->tech_pvt == op0) 
2988                         op0->ignoredtmf = 0;
2989                 else if (who->tech_pvt == op1)
2990                         op1->ignoredtmf = 0;
2991                 if (!f) {
2992                         *fo = NULL;
2993                         *rc = who;
2994                         if (slave && master)
2995                                 zt_unlink(slave, master, 1);
2996                         if (op0 == p0)
2997                                 zt_enable_ec(p0);
2998                         if (op1 == p1)
2999                                 zt_enable_ec(p1);
3000                         return 0;
3001                 }
3002                 if (f->frametype == AST_FRAME_CONTROL) {
3003                         *fo = f;
3004                         *rc = who;
3005                         if (slave && master)
3006                                 zt_unlink(slave, master, 1);
3007                         return 0;
3008                 }
3009                 if (f->frametype == AST_FRAME_DTMF) {
3010                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
3011                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
3012                                 *fo = f;
3013                                 *rc = who;
3014                                 if (slave && master)
3015                                         zt_unlink(slave, master, 1);
3016                                 return 0;
3017                         } else if ((who == c0) && p0->pulsedial) {
3018                                 ast_write(c1, f);
3019                         } else if ((who == c1) && p1->pulsedial) {
3020                                 ast_write(c0, f);
3021                         }
3022                 }
3023                 ast_frfree(f);
3024
3025                 /* Swap who gets priority */
3026                 cs[2] = cs[0];
3027                 cs[0] = cs[1];
3028                 cs[1] = cs[2];
3029         }
3030 }
3031
3032 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
3033 {
3034         struct zt_pvt *p = newchan->tech_pvt;
3035         int x;
3036         ast_mutex_lock(&p->lock);
3037         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
3038         if (p->owner == oldchan) {
3039                 p->owner = newchan;
3040         }
3041         for (x=0;x<3;x++)
3042                 if (p->subs[x].owner == oldchan) {
3043                         if (!x)
3044                                 zt_unlink(NULL, p, 0);
3045                         p->subs[x].owner = newchan;
3046                 }
3047         if (newchan->_state == AST_STATE_RINGING) 
3048                 zt_indicate(newchan, AST_CONTROL_RINGING);
3049         update_conf(p);
3050         ast_mutex_unlock(&p->lock);
3051         return 0;
3052 }
3053
3054 static int zt_ring_phone(struct zt_pvt *p)
3055 {
3056         int x;
3057         int res;
3058         /* Make sure our transmit state is on hook */
3059         x = 0;
3060         x = ZT_ONHOOK;
3061         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3062         do {
3063                 x = ZT_RING;
3064                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
3065 #if 0
3066                 printf("Res: %d, error: %s\n", res, strerror(errno));
3067 #endif                                          
3068                 if (res) {
3069                         switch(errno) {
3070                         case EBUSY:
3071                         case EINTR:
3072                                 /* Wait just in case */
3073                                 usleep(10000);
3074                                 continue;
3075                         case EINPROGRESS:
3076                                 res = 0;
3077                                 break;
3078                         default:
3079                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
3080                                 res = 0;
3081                         }
3082                 }
3083         } while (res);
3084         return res;
3085 }
3086
3087 static void *ss_thread(void *data);
3088
3089 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
3090
3091 static int attempt_transfer(struct zt_pvt *p)
3092 {
3093         /* In order to transfer, we need at least one of the channels to
3094            actually be in a call bridge.  We can't conference two applications
3095            together (but then, why would we want to?) */
3096         if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
3097                 /* The three-way person we're about to transfer to could still be in MOH, so
3098                    stop if now if appropriate */
3099                 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
3100                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
3101                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
3102                         ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
3103                 }
3104                 if (p->subs[SUB_REAL].owner->cdr) {
3105                         /* Move CDR from second channel to current one */
3106                         p->subs[SUB_THREEWAY].owner->cdr =
3107                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
3108                         p->subs[SUB_REAL].owner->cdr = NULL;
3109                 }
3110                 if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
3111                         /* Move CDR from second channel's bridge to current one */
3112                         p->subs[SUB_THREEWAY].owner->cdr =
3113                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
3114                         ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
3115                 }
3116                  if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
3117                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3118                                         ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
3119                         return -1;
3120                 }
3121                 /* Orphan the channel after releasing the lock */
3122                 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
3123                 unalloc_sub(p, SUB_THREEWAY);
3124         } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
3125                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
3126                         ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
3127                 }
3128                 ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
3129                 if (p->subs[SUB_THREEWAY].owner->cdr) {
3130                         /* Move CDR from second channel to current one */
3131                         p->subs[SUB_REAL].owner->cdr = 
3132                                 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);
3133                         p->subs[SUB_THREEWAY].owner->cdr = NULL;
3134                 }
3135                 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr) {
3136                         /* Move CDR from second channel's bridge to current one */
3137                         p->subs[SUB_REAL].owner->cdr = 
3138                                 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr);
3139                         ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->cdr = NULL;
3140                 }
3141                 if (ast_channel_masquerade(p->subs[SUB_REAL].owner, ast_bridged_channel(p->subs[SUB_THREEWAY].owner))) {
3142                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
3143                                         ast_bridged_channel(p->subs[SUB_THREEWAY].owner)->name, p->subs[SUB_REAL].owner->name);
3144                         return -1;
3145                 }
3146                 /* Three-way is now the REAL */
3147                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
3148                 ast_mutex_unlock(&p->subs[SUB_REAL].owner->lock);
3149                 unalloc_sub(p, SUB_THREEWAY);
3150                 /* Tell the caller not to hangup */
3151                 return 1;
3152         } else {
3153                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
3154                                         p->subs[SUB_REAL].owner->name, p->subs[SUB_THREEWAY].owner->name);
3155                 p->subs[SUB_THREEWAY].owner->_softhangup |= AST_SOFTHANGUP_DEV;
3156         }
3157         return 0;
3158 }
3159
3160 #ifdef ZAPATA_R2
3161 static struct ast_frame *handle_r2_event(struct zt_pvt *p, mfcr2_event_t *e, int index)
3162 {
3163         struct ast_frame *f;
3164         f = &p->subs[index].f;
3165         if (!p->r2) {
3166                 ast_log(LOG_WARNING, "Huh?  No R2 structure :(\n");
3167                 return NULL;
3168         }
3169         switch(e->e) {
3170         case MFCR2_EVENT_BLOCKED:
3171                 if (option_verbose > 2)
3172                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d blocked\n", p->channel);
3173                 break;
3174         case MFCR2_EVENT_UNBLOCKED:
3175                 if (option_verbose > 2)
3176                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d unblocked\n", p->channel);
3177                 break;
3178         case MFCR2_EVENT_CONFIG_ERR:
3179                 if (option_verbose > 2)
3180                         ast_verbose(VERBOSE_PREFIX_3 "Config error on channel %d\n", p->channel);
3181                 break;
3182         case MFCR2_EVENT_RING:
3183                 if (option_verbose > 2)
3184                         ast_verbose(VERBOSE_PREFIX_3 "Ring on channel %d\n", p->channel);
3185                 break;
3186         case MFCR2_EVENT_HANGUP:
3187                 if (option_verbose > 2)
3188                         ast_verbose(VERBOSE_PREFIX_3 "Hangup on channel %d\n", p->channel);
3189                 break;
3190         case MFCR2_EVENT_RINGING:
3191                 if (option_verbose > 2)
3192                         ast_verbose(VERBOSE_PREFIX_3 "Ringing on channel %d\n", p->channel);
3193                 break;
3194         case MFCR2_EVENT_ANSWER:
3195                 if (option_verbose > 2)
3196                         ast_verbose(VERBOSE_PREFIX_3 "Answer on channel %d\n", p->channel);
3197                 break;
3198         case MFCR2_EVENT_HANGUP_ACK:
3199                 if (option_verbose > 2)
3200                         ast_verbose(VERBOSE_PREFIX_3 "Hangup ACK on channel %d\n", p->channel);
3201                 break;
3202         case MFCR2_EVENT_IDLE:
3203                 if (option_verbose > 2)
3204                         ast_verbose(VERBOSE_PREFIX_3 "Idle on channel %d\n", p->channel);
3205                 break;
3206         default:
3207                 ast_log(LOG_WARNING, "Unknown MFC/R2 event %d\n", e->e);
3208                 break;
3209         }
3210         return f;
3211 }
3212
3213 static mfcr2_event_t *r2_get_event_bits(struct zt_pvt *p)
3214 {
3215         int x;
3216         int res;
3217         mfcr2_event_t *e;
3218         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETRXBITS, &x);
3219         if (res) {
3220                 ast_log(LOG_WARNING, "Unable to check received bits\n");
3221                 return NULL;
3222         }
3223         if (!p->r2) {
3224                 ast_log(LOG_WARNING, "Odd, no R2 structure on channel %d\n", p->channel);
3225                 return NULL;
3226         }
3227         e = mfcr2_cas_signaling_event(p->r2, x);
3228         return e;
3229 }
3230 #endif
3231
3232 static int check_for_conference(struct zt_pvt *p)
3233 {
3234         ZT_CONFINFO ci;
3235         /* Fine if we already have a master, etc */
3236         if (p->master || (p->confno > -1))
3237                 return 0;
3238         memset(&ci, 0, sizeof(ci));
3239         if (ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &ci)) {
3240                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d\n", p->channel);
3241                 return 0;
3242         }
3243         /* If we have no master and don't have a confno, then 
3244            if we're in a conference, it's probably a MeetMe room or
3245            some such, so don't let us 3-way out! */
3246         if ((p->subs[SUB_REAL].curconf.confno != ci.confno) || (p->subs[SUB_REAL].curconf.confmode != ci.confmode)) {
3247                 if (option_verbose > 2) 
3248                         ast_verbose(VERBOSE_PREFIX_3 "Avoiding 3-way call when in an external conference\n");
3249                 return 1;
3250         }
3251         return 0;
3252 }
3253
3254 static int get_alarms(struct zt_pvt *p)
3255 {
3256         int res;
3257         ZT_SPANINFO zi;
3258         memset(&zi, 0, sizeof(zi));
3259         zi.spanno = p->span;
3260         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SPANSTAT, &zi);
3261         if (res < 0) {
3262                 ast_log(LOG_WARNING, "Unable to determine alarm on channel %d\n", p->channel);
3263                 return 0;
3264         }
3265         return zi.alarms;
3266 }
3267                         
3268 static struct ast_frame *zt_handle_event(struct ast_channel *ast)
3269 {
3270         int res,x;
3271         int index;
3272         char *c;
3273         struct zt_pvt *p = ast->tech_pvt;
3274         pthread_t threadid;
3275         pthread_attr_t attr;
3276         struct ast_channel *chan;
3277         pthread_attr_init(&attr);
3278         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
3279         index = zt_get_index(ast, p, 0);
3280         p->subs[index].f.frametype = AST_FRAME_NULL;
3281         p->subs[index].f.datalen = 0;
3282         p->subs[index].f.samples = 0;
3283         p->subs[index].f.mallocd = 0;
3284         p->subs[index].f.offset = 0;
3285         p->subs[index].f.src = "zt_handle_event";
3286         p->subs[index].f.data = NULL;
3287         if (index < 0)
3288                 return &p->subs[index].f;
3289         if (p->fake_event) {
3290                 res = p->fake_event;
3291                 p->fake_event = 0;
3292         } else
3293                 res = zt_get_event(p->subs[index].zfd);
3294         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
3295         if (res & (ZT_EVENT_PULSEDIGIT | ZT_EVENT_DTMFUP)) {
3296                 if (res & ZT_EVENT_PULSEDIGIT)
3297                         p->pulsedial = 1;
3298                 else
3299                         p->pulsedial = 0;
3300                 ast_log(LOG_DEBUG, "Pulse dial '%c'\n", res & 0xff);
3301                 p->subs[index].f.frametype = AST_FRAME_DTMF;
3302                 p->subs[index].f.subclass = res & 0xff;
3303                 /* Unmute conference, return the captured digit */
3304                 zt_confmute(p, 0);
3305                 return &p->subs[index].f;
3306         }
3307         if (res & ZT_EVENT_DTMFDOWN) {
3308                 ast_log(LOG_DEBUG, "DTMF Down '%c'\n", res & 0xff);
3309                 p->subs[index].f.frametype = AST_FRAME_NULL;
3310                 p->subs[index].f.subclass = 0;
3311                 zt_confmute(p, 1);
3312                 /* Mute conference, return null frame */
3313                 return &p->subs[index].f;
3314         }
3315         switch(res) {
3316                 case ZT_EVENT_BITSCHANGED:
3317                         if (p->sig == SIG_R2) {
3318 #ifdef ZAPATA_R2
3319                                 struct ast_frame  *f = &p->subs[index].f;
3320                                 mfcr2_event_t *e;
3321                                 e = r2_get_event_bits(p);
3322                                 if (e)
3323                                         f = handle_r2_event(p, e, index);
3324                                 return f;
3325 #else                           
3326                                 break;
3327 #endif
3328                         }
3329                         ast_log(LOG_WARNING, "Recieved bits changed on %s signalling?\n", sig2str(p->sig));
3330                 case ZT_EVENT_PULSE_START:
3331                         /* Stop tone if there's a pulse start and the PBX isn't started */
3332                         if (!ast->pbx)
3333                                 tone_zone_play_tone(p->subs[index].zfd, -1);
3334                         break;  
3335                 case ZT_EVENT_DIALCOMPLETE:
3336                         if (p->inalarm) break;
3337                         if (p->radio) break;
3338                         if (ioctl(p->subs[index].zfd,ZT_DIALING,&x) == -1) {
3339                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
3340                                 return NULL;
3341                         }
3342                         if (!x) { /* if not still dialing in driver */
3343                                 zt_enable_ec(p);
3344                                 if (p->echobreak) {
3345                                         zt_train_ec(p);
3346                                         ast_copy_string(p->dop.dialstr, p->echorest, sizeof(p->dop.dialstr));
3347                                         p->dop.op = ZT_DIAL_OP_REPLACE;
3348                                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop);
3349                                         p->echobreak = 0;
3350                                 } else {
3351                                         p->dialing = 0;
3352                                         if (p->sig == SIG_E911) {
3353                                                 /* if thru with dialing after offhook */
3354                                                 if (ast->_state == AST_STATE_DIALING_OFFHOOK) {
3355                                                         ast_setstate(ast, AST_STATE_UP);
3356                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3357                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3358                                                         break;
3359                                                 } else { /* if to state wait for offhook to dial rest */
3360                                                         /* we now wait for off hook */
3361                                                         ast_setstate(ast,AST_STATE_DIALING_OFFHOOK);
3362                                                 }
3363                                         }
3364                                         if (ast->_state == AST_STATE_DIALING) {
3365                                                 if ((p->callprogress & 1) && CANPROGRESSDETECT(p) && p->dsp && p->outgoing) {
3366                                                         ast_log(LOG_DEBUG, "Done dialing, but waiting for progress detection before doing more...\n");
3367                                                 } 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)))) {
3368                                                         ast_setstate(ast, AST_STATE_RINGING);
3369                                                 } else if (!p->answeronpolarityswitch) {
3370                                                         ast_setstate(ast, AST_STATE_UP);
3371                                                         p->subs[index].f.frametype = AST_FRAME_CONTROL;
3372                                                         p->subs[index].f.subclass = AST_CONTROL_ANSWER;
3373                                                 }
3374                                         }
3375                                 }
3376                         }
3377                         break;