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