Merge mog's ReadFile application (bug #3670)
[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 #ifdef ZAPATA_R2
1001 static int str2r2prot(char *swtype)
1002 {
1003     if (!strcasecmp(swtype, "ar"))
1004         return MFCR2_PROT_ARGENTINA;
1005     /*endif*/
1006     if (!strcasecmp(swtype, "cn"))
1007         return MFCR2_PROT_CHINA;
1008     /*endif*/
1009     if (!strcasecmp(swtype, "kr"))
1010         return MFCR2_PROT_KOREA;
1011     /*endif*/
1012     return -1;
1013 }
1014 #endif
1015
1016 static char *sig2str(int sig)
1017 {
1018         static char buf[256];
1019         switch(sig) {
1020         case SIG_EM:
1021                 return "E & M Immediate";
1022         case SIG_EMWINK:
1023                 return "E & M Wink";
1024         case SIG_EM_E1:
1025                 return "E & M E1";
1026         case SIG_FEATD:
1027                 return "Feature Group D (DTMF)";
1028         case SIG_FEATDMF:
1029                 return "Feature Group D (MF)";
1030         case SIG_FEATB:
1031                 return "Feature Group B (MF)";
1032         case SIG_E911:
1033                 return "E911 (MF)";
1034         case SIG_FXSLS:
1035                 return "FXS Loopstart";
1036         case SIG_FXSGS:
1037                 return "FXS Groundstart";
1038         case SIG_FXSKS:
1039                 return "FXS Kewlstart";
1040         case SIG_FXOLS:
1041                 return "FXO Loopstart";
1042         case SIG_FXOGS:
1043                 return "FXO Groundstart";
1044         case SIG_FXOKS:
1045                 return "FXO Kewlstart";
1046         case SIG_PRI:
1047                 return "PRI Signalling";
1048         case SIG_R2:
1049                 return "R2 Signalling";
1050         case SIG_SF:
1051                 return "SF (Tone) Signalling Immediate";
1052         case SIG_SFWINK:
1053                 return "SF (Tone) Signalling Wink";
1054         case SIG_SF_FEATD:
1055                 return "SF (Tone) Signalling with Feature Group D (DTMF)";
1056         case SIG_SF_FEATDMF:
1057                 return "SF (Tone) Signalling with Feature Group D (MF)";
1058         case SIG_SF_FEATB:
1059                 return "SF (Tone) Signalling with Feature Group B (MF)";
1060         case SIG_GR303FXOKS:
1061                 return "GR-303 Signalling with FXOKS";
1062         case SIG_GR303FXSKS:
1063                 return "GR-303 Signalling with FXSKS";
1064         case 0:
1065                 return "Pseudo Signalling";
1066         default:
1067                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1068                 return buf;
1069         }
1070 }
1071
1072 static int conf_add(struct zt_pvt *p, struct zt_subchannel *c, int index, int slavechannel)
1073 {
1074         /* If the conference already exists, and we're already in it
1075            don't bother doing anything */
1076         ZT_CONFINFO zi;
1077         
1078         memset(&zi, 0, sizeof(zi));
1079         zi.chan = 0;
1080
1081         if (slavechannel > 0) {
1082                 /* If we have only one slave, do a digital mon */
1083                 zi.confmode = ZT_CONF_DIGITALMON;
1084                 zi.confno = slavechannel;
1085         } else {
1086                 if (!index) {
1087                         /* Real-side and pseudo-side both participate in conference */
1088                         zi.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER |
1089                                                                 ZT_CONF_PSEUDO_TALKER | ZT_CONF_PSEUDO_LISTENER;
1090                 } else
1091                         zi.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
1092                 zi.confno = p->confno;
1093         }
1094         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1095                 return 0;
1096         if (c->zfd < 0)
1097                 return 0;
1098         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1099                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1100                 return -1;
1101         }
1102         if (slavechannel < 1) {
1103                 p->confno = zi.confno;
1104         }
1105         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1106         ast_log(LOG_DEBUG, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1107         return 0;
1108 }
1109
1110 static int isourconf(struct zt_pvt *p, struct zt_subchannel *c)
1111 {
1112         /* If they're listening to our channel, they're ours */ 
1113         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == ZT_CONF_DIGITALMON))
1114                 return 1;
1115         /* If they're a talker on our (allocated) conference, they're ours */
1116         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & ZT_CONF_TALKER))
1117                 return 1;
1118         return 0;
1119 }
1120
1121 static int conf_del(struct zt_pvt *p, struct zt_subchannel *c, int index)
1122 {
1123         ZT_CONFINFO zi;
1124         if (/* Can't delete if there's no zfd */
1125                 (c->zfd < 0) ||
1126                 /* Don't delete from the conference if it's not our conference */
1127                 !isourconf(p, c)
1128                 /* Don't delete if we don't think it's conferenced at all (implied) */
1129                 ) return 0;
1130         memset(&zi, 0, sizeof(zi));
1131         zi.chan = 0;
1132         zi.confno = 0;
1133         zi.confmode = 0;
1134         if (ioctl(c->zfd, ZT_SETCONF, &zi)) {
1135                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1136                 return -1;
1137         }
1138         ast_log(LOG_DEBUG, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1139         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1140         return 0;
1141 }
1142
1143 static int isslavenative(struct zt_pvt *p, struct zt_pvt **out)
1144 {
1145         int x;
1146         int useslavenative;
1147         struct zt_pvt *slave = NULL;
1148         /* Start out optimistic */
1149         useslavenative = 1;
1150         /* Update conference state in a stateless fashion */
1151         for (x=0;x<3;x++) {
1152                 /* Any three-way calling makes slave native mode *definitely* out
1153                    of the question */
1154                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1155                         useslavenative = 0;
1156         }
1157         /* If we don't have any 3-way calls, check to see if we have
1158            precisely one slave */
1159         if (useslavenative) {
1160                 for (x=0;x<MAX_SLAVES;x++) {
1161                         if (p->slaves[x]) {
1162                                 if (slave) {
1163                                         /* Whoops already have a slave!  No 
1164                                            slave native and stop right away */
1165                                         slave = NULL;
1166                                         useslavenative = 0;
1167                                         break;
1168                                 } else {
1169                                         /* We have one slave so far */
1170                                         slave = p->slaves[x];
1171                                 }
1172                         }
1173                 }
1174         }
1175         /* If no slave, slave native definitely out */
1176         if (!slave)
1177                 useslavenative = 0;
1178         else if (slave->law != p->law) {
1179                 useslavenative = 0;
1180                 slave = NULL;
1181         }
1182         if (out)
1183                 *out = slave;
1184         return useslavenative;
1185 }
1186
1187 static int reset_conf(struct zt_pvt *p)
1188 {
1189         ZT_CONFINFO zi;
1190         memset(&zi, 0, sizeof(zi));
1191         p->confno = -1;
1192         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1193         if (p->subs[SUB_REAL].zfd > -1) {
1194                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &zi))
1195                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1196         }
1197         return 0;
1198 }
1199
1200 static int update_conf(struct zt_pvt *p)
1201 {
1202         int needconf = 0;
1203         int x;
1204         int useslavenative;
1205         struct zt_pvt *slave = NULL;
1206
1207         useslavenative = isslavenative(p, &slave);
1208         /* Start with the obvious, general stuff */
1209         for (x=0;x<3;x++) {
1210                 /* Look for three way calls */
1211                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1212                         conf_add(p, &p->subs[x], x, 0);
1213                         needconf++;
1214                 } else {
1215                         conf_del(p, &p->subs[x], x);
1216                 }
1217         }
1218         /* If we have a slave, add him to our conference now. or DAX
1219            if this is slave native */
1220         for (x=0;x<MAX_SLAVES;x++) {
1221                 if (p->slaves[x]) {
1222                         if (useslavenative)
1223                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1224                         else {
1225                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1226                                 needconf++;
1227                         }
1228                 }
1229         }
1230         /* If we're supposed to be in there, do so now */
1231         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1232                 if (useslavenative)
1233                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1234                 else {
1235                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1236                         needconf++;
1237                 }
1238         }
1239         /* If we have a master, add ourselves to his conference */
1240         if (p->master) {
1241                 if (isslavenative(p->master, NULL)) {
1242                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1243                 } else {
1244                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1245                 }
1246         }
1247         if (!needconf) {
1248                 /* Nobody is left (or should be left) in our conference.  
1249                    Kill it.  */
1250                 p->confno = -1;
1251         }
1252         ast_log(LOG_DEBUG, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1253         return 0;
1254 }
1255
1256 static void zt_enable_ec(struct zt_pvt *p)
1257 {
1258         int x;
1259         int res;
1260         if (!p)
1261                 return;
1262         if (p->echocanon) {
1263                 ast_log(LOG_DEBUG, "Echo cancellation already on\n");
1264                 return;
1265         }
1266         if (p->digital) {
1267                 ast_log(LOG_DEBUG, "Echo cancellation isn't required on digital connection\n");
1268                 return;
1269         }
1270         if (p->echocancel) {
1271                 if (p->sig == SIG_PRI) {
1272                         x = 1;
1273                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x);
1274                         if (res)
1275                                 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1276                 }
1277                 x = p->echocancel;
1278                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1279                 if (res) 
1280                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
1281                 else {
1282                         p->echocanon = 1;
1283                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
1284                 }
1285         } else
1286                 ast_log(LOG_DEBUG, "No echo cancellation requested\n");
1287 }
1288
1289 static void zt_train_ec(struct zt_pvt *p)
1290 {
1291         int x;
1292         int res;
1293         if (p && p->echocancel && p->echotraining) {
1294                 x = p->echotraining;
1295                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOTRAIN, &x);
1296                 if (res) 
1297                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1298                 else {
1299                         ast_log(LOG_DEBUG, "Engaged echo training on channel %d\n", p->channel);
1300                 }
1301         } else
1302                 ast_log(LOG_DEBUG, "No echo training requested\n");
1303 }
1304
1305 static void zt_disable_ec(struct zt_pvt *p)
1306 {
1307         int x;
1308         int res;
1309         if (p->echocancel) {
1310                 x = 0;
1311                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_ECHOCANCEL, &x);
1312                 if (res) 
1313                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1314                 else
1315                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
1316         }
1317         p->echocanon = 0;
1318 }
1319
1320 int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1321 {
1322         struct  zt_gains g;
1323         float ltxgain;
1324         float lrxgain;
1325         int j,k;
1326         g.chan = chan;
1327         if ((rxgain != 0.0)  || (txgain != 0.0)) {
1328                 /* caluculate linear value of tx gain */
1329                 ltxgain = pow(10.0,txgain / 20.0);
1330                 /* caluculate linear value of rx gain */
1331                 lrxgain = pow(10.0,rxgain / 20.0);
1332                 if (law == ZT_LAW_ALAW) {
1333                         for (j=0;j<256;j++) {
1334                                 k = (int)(((float)AST_ALAW(j)) * lrxgain);
1335                                 if (k > 32767) k = 32767;
1336                                 if (k < -32767) k = -32767;
1337                                 g.rxgain[j] = AST_LIN2A(k);
1338                                 k = (int)(((float)AST_ALAW(j)) * ltxgain);
1339                                 if (k > 32767) k = 32767;
1340                                 if (k < -32767) k = -32767;
1341                                 g.txgain[j] = AST_LIN2A(k);
1342                         }
1343                 } else {
1344                         for (j=0;j<256;j++) {
1345                                 k = (int)(((float)AST_MULAW(j)) * lrxgain);
1346                                 if (k > 32767) k = 32767;
1347                                 if (k < -32767) k = -32767;
1348                                 g.rxgain[j] = AST_LIN2MU(k);
1349                                 k = (int)(((float)AST_MULAW(j)) * ltxgain);
1350                                 if (k > 32767) k = 32767;
1351                                 if (k < -32767) k = -32767;
1352                                 g.txgain[j] = AST_LIN2MU(k);
1353                         }
1354                 }
1355         } else {
1356                 for (j=0;j<256;j++) {
1357                         g.rxgain[j] = j;
1358                         g.txgain[j] = j;
1359                 }
1360         }
1361                 
1362           /* set 'em */
1363         return(ioctl(fd,ZT_SETGAINS,&g));
1364 }
1365
1366 static inline int zt_set_hook(int fd, int hs)
1367 {
1368         int x, res;
1369         x = hs;
1370         res = ioctl(fd, ZT_HOOK, &x);
1371         if (res < 0) 
1372         {
1373                 if (errno == EINPROGRESS) return 0;
1374                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
1375         }
1376         return res;
1377 }
1378
1379 static inline int zt_confmute(struct zt_pvt *p, int muted)
1380 {
1381         int x, y, res;
1382         x = muted;
1383         if (p->sig == SIG_PRI) {
1384                 y = 1;
1385                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &y);
1386                 if (res)
1387                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1388         }
1389         res = ioctl(p->subs[SUB_REAL].zfd, ZT_CONFMUTE, &x);
1390         if (res < 0) 
1391                 ast_log(LOG_WARNING, "zt confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1392         return res;
1393 }
1394
1395 static int save_conference(struct zt_pvt *p)
1396 {
1397         struct zt_confinfo c;
1398         int res;
1399         if (p->saveconf.confmode) {
1400                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1401                 return -1;
1402         }
1403         p->saveconf.chan = 0;
1404         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GETCONF, &p->saveconf);
1405         if (res) {
1406                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1407                 p->saveconf.confmode = 0;
1408                 return -1;
1409         }
1410         c.chan = 0;
1411         c.confno = 0;
1412         c.confmode = ZT_CONF_NORMAL;
1413         res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &c);
1414         if (res) {
1415                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1416                 return -1;
1417         }
1418         if (option_debug)
1419                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
1420         return 0;
1421 }
1422
1423 static int restore_conference(struct zt_pvt *p)
1424 {
1425         int res;
1426         if (p->saveconf.confmode) {
1427                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETCONF, &p->saveconf);
1428                 p->saveconf.confmode = 0;
1429                 if (res) {
1430                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1431                         return -1;
1432                 }
1433         }
1434         if (option_debug)
1435                 ast_log(LOG_DEBUG, "Restored conferencing\n");
1436         return 0;
1437 }
1438
1439 static int send_callerid(struct zt_pvt *p);
1440
1441 int send_cwcidspill(struct zt_pvt *p)
1442 {
1443         p->callwaitcas = 0;
1444         p->cidcwexpire = 0;
1445         p->cidspill = malloc(MAX_CALLERID_SIZE);
1446         if (p->cidspill) {
1447                 memset(p->cidspill, 0x7f, MAX_CALLERID_SIZE);
1448                 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1449                 /* Make sure we account for the end */
1450                 p->cidlen += READ_SIZE * 4;
1451                 p->cidpos = 0;
1452                 send_callerid(p);
1453                 if (option_verbose > 2)
1454                         ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1455         } else return -1;
1456         return 0;
1457 }
1458
1459 static int has_voicemail(struct zt_pvt *p)
1460 {
1461
1462         return ast_app_has_voicemail(p->mailbox, NULL);
1463 }
1464
1465 static int send_callerid(struct zt_pvt *p)
1466 {
1467         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
1468         int res;
1469         /* Take out of linear mode if necessary */
1470         if (p->subs[SUB_REAL].linear) {
1471                 p->subs[SUB_REAL].linear = 0;
1472                 zt_setlinear(p->subs[SUB_REAL].zfd, 0);
1473         }
1474         while(p->cidpos < p->cidlen) {
1475                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
1476                 if (res < 0) {
1477                         if (errno == EAGAIN)
1478                                 return 0;
1479                         else {
1480                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
1481                                 return -1;
1482                         }
1483                 }
1484                 if (!res)
1485                         return 0;
1486                 p->cidpos += res;
1487         }
1488         free(p->cidspill);
1489         p->cidspill = NULL;
1490         if (p->callwaitcas) {
1491                 /* Wait for CID/CW to expire */
1492                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
1493         } else
1494                 restore_conference(p);
1495         return 0;
1496 }
1497
1498 static int zt_callwait(struct ast_channel *ast)
1499 {
1500         struct zt_pvt *p = ast->pvt->pvt;
1501         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1502         if (p->cidspill) {
1503                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1504                 free(p->cidspill);
1505         }
1506         p->cidspill = malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4);
1507         if (p->cidspill) {
1508                 save_conference(p);
1509                 /* Silence */
1510                 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1511                 if (!p->callwaitrings && p->callwaitingcallerid) {
1512                         ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1513                         p->callwaitcas = 1;
1514                         p->cidlen = 2400 + 680 + READ_SIZE * 4;
1515                 } else {
1516                         ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1517                         p->callwaitcas = 0;
1518                         p->cidlen = 2400 + READ_SIZE * 4;
1519                 }
1520                 p->cidpos = 0;
1521                 send_callerid(p);
1522         } else {
1523                 ast_log(LOG_WARNING, "Unable to create SAS/CAS spill\n");
1524                 return -1;
1525         }
1526         return 0;
1527 }
1528
1529 static int zt_call(struct ast_channel *ast, char *rdest, int timeout)
1530 {
1531         struct zt_pvt *p = ast->pvt->pvt;
1532         int x, res, index;
1533         char *c, *n, *l;
1534 #ifdef ZAPATA_PRI
1535         char *s=NULL;
1536 #endif
1537         char dest[256]; /* must be same length as p->dialdest */
1538         ast_mutex_lock(&p->lock);
1539         strncpy(dest, rdest, sizeof(dest) - 1);
1540         strncpy(p->dialdest, rdest, sizeof(dest) - 1);
1541         if ((ast->_state == AST_STATE_BUSY)) {
1542                 p->subs[SUB_REAL].needbusy = 1;
1543                 ast_mutex_unlock(&p->lock);
1544                 return 0;
1545         }
1546         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
1547                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
1548                 ast_mutex_unlock(&p->lock);
1549                 return -1;
1550         }
1551         p->dialednone = 0;
1552         if (p->radio)  /* if a radio channel, up immediately */
1553         {
1554                 /* Special pseudo -- automatically up */
1555                 ast_setstate(ast, AST_STATE_UP); 
1556                 ast_mutex_unlock(&p->lock);
1557                 return 0;
1558         }
1559         x = ZT_FLUSH_READ | ZT_FLUSH_WRITE;
1560         res = ioctl(p->subs[SUB_REAL].zfd, ZT_FLUSH, &x);
1561         if (res)
1562                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
1563         p->outgoing = 1;
1564
1565         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1566
1567         switch(p->sig) {
1568         case SIG_FXOLS:
1569         case SIG_FXOGS:
1570         case SIG_FXOKS:
1571                 if (p->owner == ast) {
1572                         /* Normal ring, on hook */
1573                         
1574                         /* Don't send audio while on hook, until the call is answered */
1575                         p->dialing = 1;
1576                         if (p->use_callerid) {
1577                                 /* Generate the Caller-ID spill if desired */
1578                                 if (p->cidspill) {
1579                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
1580                                         free(p->cidspill);
1581                                 }
1582                                 p->cidspill = malloc(MAX_CALLERID_SIZE);
1583                                 p->callwaitcas = 0;
1584                                 if (p->cidspill) {
1585                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
1586                                         p->cidpos = 0;
1587                                         send_callerid(p);
1588                                 } else
1589                                         ast_log(LOG_WARNING, "Unable to generate CallerID spill\n");
1590                         }
1591                         /* Choose proper cadence */
1592                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1593                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, &cadences[p->distinctivering-1]))
1594                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
1595                                 p->cidrings = cidrings[p->distinctivering - 1];
1596                         } else {
1597                                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_SETCADENCE, NULL))
1598                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
1599                                 p->cidrings = p->sendcalleridafter;
1600                         }
1601
1602
1603                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
1604                         c = strchr(dest, '/');
1605                         if (c)
1606                                 c++;
1607                         if (c && (strlen(c) < p->stripmsd)) {
1608                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1609                                 c = NULL;
1610                         }
1611                         if (c) {
1612                                 p->dop.op = ZT_DIAL_OP_REPLACE;
1613                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
1614                                 ast_log(LOG_DEBUG, "FXO: setup deferred dialstring: %s\n", c);
1615                         } else {
1616                                 p->dop.dialstr[0] = '\0';
1617                         }
1618                         x = ZT_RING;
1619                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x) && (errno != EINPROGRESS)) {
1620                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
1621                                 ast_mutex_unlock(&p->lock);
1622                                 return -1;
1623                         }
1624                         p->dialing = 1;
1625                 } else {
1626                         /* Call waiting call */
1627                         p->callwaitrings = 0;
1628                         if (ast->cid.cid_num)
1629                                 strncpy(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num)-1);
1630                         else
1631                                 p->callwait_num[0] = '\0';
1632                         if (ast->cid.cid_name)
1633                                 strncpy(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name)-1);
1634                         else
1635                                 p->callwait_name[0] = '\0';
1636                         /* Call waiting tone instead */
1637                         if (zt_callwait(ast)) {
1638                                 ast_mutex_unlock(&p->lock);
1639                                 return -1;
1640                         }
1641                         /* Make ring-back */
1642                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, ZT_TONE_RINGTONE))
1643                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
1644                                 
1645                 }
1646                 n = ast->cid.cid_name;
1647                 l = ast->cid.cid_num;
1648                 if (l)
1649                         strncpy(p->lastcid_num, l, sizeof(p->lastcid_num) - 1);
1650                 else
1651                         p->lastcid_num[0] = '\0';
1652                 if (n)
1653                         strncpy(p->lastcid_name, n, sizeof(p->lastcid_name) - 1);
1654                 else
1655                         p->lastcid_name[0] = '\0';
1656                 ast_setstate(ast, AST_STATE_RINGING);
1657                 index = zt_get_index(ast, p, 0);
1658                 if (index > -1) {
1659                         p->subs[index].needringing = 1;
1660                 }
1661                 break;
1662         case SIG_FXSLS:
1663         case SIG_FXSGS:
1664         case SIG_FXSKS:
1665         case SIG_EMWINK:
1666         case SIG_EM:
1667         case SIG_EM_E1:
1668         case SIG_FEATD:
1669         case SIG_FEATDMF:
1670         case SIG_E911:
1671         case SIG_FEATB:
1672         case SIG_SFWINK:
1673         case SIG_SF:
1674         case SIG_SF_FEATD:
1675         case SIG_SF_FEATDMF:
1676         case SIG_SF_FEATB:
1677                 c = strchr(dest, '/');
1678                 if (c)
1679                         c++;
1680                 else
1681                         c = "";
1682                 if (strlen(c) < p->stripmsd) {
1683                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1684                         ast_mutex_unlock(&p->lock);
1685                         return -1;
1686                 }
1687 #ifdef ZAPATA_PRI
1688                 /* Start the trunk, if not GR-303 */
1689                 if (!p->pri) {
1690 #endif
1691                         x = ZT_START;
1692                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1693                         if (res < 0) {
1694                                 if (errno != EINPROGRESS) {
1695                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
1696                                         ast_mutex_unlock(&p->lock);
1697                                         return -1;
1698                                 }
1699                         }
1700 #ifdef ZAPATA_PRI
1701                 }
1702 #endif
1703                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1704                 p->dop.op = ZT_DIAL_OP_REPLACE;
1705                 if (p->sig == SIG_FEATD) {
1706                         l = ast->cid.cid_num;
1707                         if (l) 
1708                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c + p->stripmsd);
1709                         else
1710                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c + p->stripmsd);
1711                 } else 
1712                 if (p->sig == SIG_FEATDMF) {
1713                         l = ast->cid.cid_num;
1714                         if (l) 
1715                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c + p->stripmsd);
1716                         else
1717                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c + p->stripmsd);
1718                 } else 
1719                 if (p->sig == SIG_E911) {
1720                         strncpy(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr) - 1);
1721                 } else
1722                 if (p->sig == SIG_FEATB) {
1723                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c + p->stripmsd);
1724                 } else 
1725                 if(p->pulse)
1726                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c + p->stripmsd);
1727                 else
1728                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c + p->stripmsd);
1729                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
1730                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
1731                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
1732                         p->echorest[sizeof(p->echorest) - 1] = '\0';
1733                         p->echobreak = 1;
1734                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
1735                 } else
1736                         p->echobreak = 0;
1737                 if (!res) {
1738                         if (ioctl(p->subs[SUB_REAL].zfd, ZT_DIAL, &p->dop)) {
1739                                 x = ZT_ONHOOK;
1740                                 ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
1741                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1742                                 ast_mutex_unlock(&p->lock);
1743                                 return -1;
1744                         }
1745                 } else
1746                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1747                 p->dialing = 1;
1748                 if (strlen(c + p->stripmsd) < 1) p->dialednone = 1;
1749                 ast_setstate(ast, AST_STATE_DIALING);
1750                 break;
1751         case 0:
1752                 /* Special pseudo -- automatically up*/
1753                 ast_setstate(ast, AST_STATE_UP);
1754                 break;          
1755         case SIG_PRI:
1756                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
1757                 p->dialdest[0] = '\0';
1758                 break;
1759         default:
1760                 ast_log(LOG_DEBUG, "not yet implemented\n");
1761                 ast_mutex_unlock(&p->lock);
1762                 return -1;
1763         }
1764 #ifdef ZAPATA_PRI
1765         if (p->pri) {
1766                 struct pri_sr *sr;
1767                 c = strchr(dest, '/');
1768                 if (c)
1769                         c++;
1770                 else
1771                         c = dest;
1772                 if (!p->hidecallerid) {
1773                         l = ast->cid.cid_num;
1774                         n = ast->cid.cid_name;
1775                 } else {
1776                         l = NULL;
1777                         n = NULL;
1778                 }
1779                 if (strlen(c) < p->stripmsd) {
1780                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1781                         ast_mutex_unlock(&p->lock);
1782                         return -1;
1783                 }
1784                 if (p->sig != SIG_FXSKS) {
1785                         p->dop.op = ZT_DIAL_OP_REPLACE;
1786                         s = strchr(c + p->stripmsd, 'w');
1787                         if (s) {
1788                                 if (strlen(s))
1789                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
1790                                 else
1791                                         p->dop.dialstr[0] = '\0';
1792                                 *s = '\0';
1793                         } else {
1794                                 p->dop.dialstr[0] = '\0';
1795                         }
1796                 }
1797                 if (pri_grab(p, p->pri)) {
1798                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
1799                         ast_mutex_unlock(&p->lock);
1800                         return -1;
1801                 }
1802                 if (!(p->call = pri_new_call(p->pri->pri))) {
1803                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
1804                         pri_rel(p->pri);
1805                         ast_mutex_unlock(&p->lock);
1806                         return -1;
1807                 }
1808                 if (!(sr = pri_sr_new())) {
1809                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
1810                         pri_rel(p->pri);
1811                         ast_mutex_unlock(&p->lock);
1812                 }
1813                 if (p->bearer || (p->sig == SIG_FXSKS)) {
1814                         if (p->bearer) {
1815                                 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);
1816                                 p->bearer->call = p->call;
1817                         } else
1818                                 ast_log(LOG_DEBUG, "I'm being setup with no bearer right now...\n");
1819                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
1820                 }
1821                 p->digital = ast_test_flag(ast,AST_FLAG_DIGITAL);
1822                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), 
1823                                                                 p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1);
1824                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : PRI_TRANS_CAP_SPEECH, 
1825                                         (p->digital ? -1 : 
1826                                                 ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
1827                 pri_sr_set_called(sr, c + p->stripmsd, p->pri->dialplan - 1,  s ? 1 : 0);
1828                 pri_sr_set_caller(sr, l, n, p->pri->localdialplan - 1, 
1829                                         l ? (p->use_callingpres ? ast->cid.cid_pres : PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN) : 
1830                                                  PRES_NUMBER_NOT_AVAILABLE);
1831                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, PRI_REDIR_UNCONDITIONAL);
1832                 if (pri_setup(p->pri->pri, p->call,  sr)) {
1833                         ast_log(LOG_WARNING, "Unable to setup call to %s\n", c + p->stripmsd);
1834                         pri_rel(p->pri);
1835                         ast_mutex_unlock(&p->lock);
1836                         pri_sr_free(sr);
1837                         return -1;
1838                 }
1839                 pri_sr_free(sr);
1840                 ast_setstate(ast, AST_STATE_DIALING);
1841                 pri_rel(p->pri);
1842         }
1843 #endif          
1844         ast_mutex_unlock(&p->lock);
1845         return 0;
1846 }
1847
1848 static void destroy_zt_pvt(struct zt_pvt **pvt)
1849 {
1850         struct zt_pvt *p = *pvt;
1851         /* Remove channel from the list */
1852         if(p->prev)
1853                 p->prev->next = p->next;
1854         if(p->next)
1855                 p->next->prev = p->prev;
1856         ast_mutex_destroy(&p->lock);
1857         free(p);
1858         *pvt = NULL;
1859 }
1860
1861 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1862 {
1863         int owned = 0;
1864         int i = 0;
1865
1866         if (!now) {
1867                 if (cur->owner) {
1868                         owned = 1;
1869                 }
1870
1871                 for (i = 0; i < 3; i++) {
1872                         if (cur->subs[i].owner) {
1873                                 owned = 1;
1874                         }
1875                 }
1876                 if (!owned) {
1877                         if (prev) {
1878                                 prev->next = cur->next;
1879                                 if (prev->next)
1880                                         prev->next->prev = prev;
1881                                 else
1882                                         ifend = prev;
1883                         } else {
1884                                 iflist = cur->next;
1885                                 if (iflist)
1886                                         iflist->prev = NULL;
1887                                 else
1888                                         ifend = NULL;
1889                         }
1890                         if (cur->subs[SUB_REAL].zfd > -1) {
1891                                 zt_close(cur->subs[SUB_REAL].zfd);
1892                         }
1893                         destroy_zt_pvt(&cur);
1894                 }
1895         } else {
1896                 if (prev) {
1897                         prev->next = cur->next;
1898                         if (prev->next)
1899                                 prev->next->prev = prev;
1900                         else
1901                                 ifend = prev;
1902                 } else {
1903                         iflist = cur->next;
1904                         if (iflist)
1905                                 iflist->prev = NULL;
1906                         else
1907                                 ifend = NULL;
1908                 }
1909                 if (cur->subs[SUB_REAL].zfd > -1) {
1910                         zt_close(cur->subs[SUB_REAL].zfd);
1911                 }
1912                 destroy_zt_pvt(&cur);
1913         }
1914         return 0;
1915 }
1916
1917 #ifdef ZAPATA_PRI
1918 int pri_is_up(struct zt_pri *pri)
1919 {
1920         int x;
1921         for (x=0;x<NUM_DCHANS;x++) {
1922                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
1923                         return 1;
1924         }
1925         return 0;
1926 }
1927
1928 int pri_assign_bearer(struct zt_pvt *crv, struct zt_pri *pri, struct zt_pvt *bearer)
1929 {
1930         bearer->owner = &inuse;
1931         bearer->realcall = crv;
1932         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
1933         if (crv->subs[SUB_REAL].owner)
1934                 crv->subs[SUB_REAL].owner->fds[0] = crv->subs[SUB_REAL].zfd;
1935         crv->bearer = bearer;
1936         crv->call = bearer->call;
1937         crv->pri = pri;
1938         return 0;
1939 }
1940
1941 static char *pri_order(int level)
1942 {
1943         switch(level) {
1944         case 0:
1945                 return "Primary";
1946         case 1:
1947                 return "Secondary";
1948         case 2:
1949                 return "Tertiary";
1950         case 3:
1951                 return "Quaternary";
1952         default:
1953                 return "<Unknown>";
1954         }               
1955 }
1956
1957 int pri_find_dchan(struct zt_pri *pri)
1958 {
1959         int oldslot = -1;
1960         struct pri *old;
1961         int newslot = -1;
1962         int x;
1963         old = pri->pri;
1964         for(x=0;x<NUM_DCHANS;x++) {
1965                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
1966                         newslot = x;
1967                 if (pri->dchans[x] == old) {
1968                         oldslot = x;
1969                 }
1970         }
1971         if (newslot < 0) {
1972                 newslot = 0;
1973                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary on channel anyway %d!\n",
1974                         pri->dchannels[newslot]);
1975         }
1976         if (old && (oldslot != newslot))
1977                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
1978                         pri->dchannels[oldslot], pri->dchannels[newslot]);
1979         pri->pri = pri->dchans[newslot];
1980         return 0;
1981 }
1982 #endif
1983
1984 static int zt_hangup(struct ast_channel *ast)
1985 {
1986         int res;
1987         int index,x, law;
1988         /*static int restore_gains(struct zt_pvt *p);*/
1989         struct zt_pvt *p = ast->pvt->pvt;
1990         struct zt_pvt *tmp = NULL;
1991         struct zt_pvt *prev = NULL;
1992         ZT_PARAMS par;
1993
1994         if (option_debug)
1995                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
1996         if (!ast->pvt->pvt) {
1997                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1998                 return 0;
1999         }
2000         
2001         ast_mutex_lock(&p->lock);
2002         
2003         index = zt_get_index(ast, p, 1);
2004
2005         if (p->sig == SIG_PRI) {
2006                 x = 1;
2007                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2008         }
2009
2010         x = 0;
2011         zt_confmute(p, 0);
2012         restore_gains(p);
2013         if (p->origcid_num) {
2014                 strncpy(p->cid_num, p->origcid_num, sizeof(p->cid_num) - 1);
2015                 free(p->origcid_num);
2016                 p->origcid_num = NULL;
2017         }       
2018         if (p->origcid_name) {
2019                 strncpy(p->cid_name, p->origcid_name, sizeof(p->cid_name) - 1);
2020                 free(p->origcid_name);
2021                 p->origcid_name = NULL;
2022         }       
2023         if (p->dsp)
2024                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);
2025         if (p->exten)
2026                 p->exten[0] = '\0';
2027
2028         ast_log(LOG_DEBUG, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
2029                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
2030         p->ignoredtmf = 0;
2031         
2032         if (index > -1) {
2033                 /* Real channel, do some fixup */
2034                 p->subs[index].owner = NULL;
2035                 p->subs[index].needanswer = 0;
2036                 p->subs[index].needflash = 0;
2037                 p->subs[index].needringing = 0;
2038                 p->subs[index].needbusy = 0;
2039                 p->subs[index].needcongestion = 0;
2040                 p->subs[index].linear = 0;
2041                 p->subs[index].needcallerid = 0;
2042                 p->polarity = POLARITY_IDLE;
2043                 zt_setlinear(p->subs[index].zfd, 0);
2044                 if (index == SUB_REAL) {
2045                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
2046                                 ast_log(LOG_DEBUG, "Normal call hung up with both three way call and a call waiting call in place?\n");
2047                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
2048                                         /* We had flipped over to answer a callwait and now it's gone */
2049                                         ast_log(LOG_DEBUG, "We were flipped over to the callwait, moving back and unowning.\n");
2050                                         /* Move to the call-wait, but un-own us until they flip back. */
2051                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2052                                         unalloc_sub(p, SUB_CALLWAIT);
2053                                         p->owner = NULL;
2054                                 } else {
2055                                         /* The three way hung up, but we still have a call wait */
2056                                         ast_log(LOG_DEBUG, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
2057                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
2058                                         unalloc_sub(p, SUB_THREEWAY);
2059                                         if (p->subs[SUB_REAL].inthreeway) {
2060                                                 /* This was part of a three way call.  Immediately make way for
2061                                                    another call */
2062                                                 ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2063                                                 p->owner = p->subs[SUB_REAL].owner;
2064                                         } else {
2065                                                 /* This call hasn't been completed yet...  Set owner to NULL */
2066                                                 ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2067                                                 p->owner = NULL;
2068                                         }
2069                                         p->subs[SUB_REAL].inthreeway = 0;
2070                                 }
2071                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
2072                                 /* Move to the call-wait and switch back to them. */
2073                                 swap_subs(p, SUB_CALLWAIT, SUB_REAL);
2074                                 unalloc_sub(p, SUB_CALLWAIT);
2075                                 p->owner = p->subs[SUB_REAL].owner;
2076                                 if (p->owner->_state != AST_STATE_UP)
2077                                         p->subs[SUB_REAL].needanswer = 1;
2078                                 if (ast_bridged_channel(p->subs[SUB_REAL].owner))
2079                                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_REAL].owner));
2080                         } else if (p->subs[SUB_THREEWAY].zfd > -1) {
2081                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2082                                 unalloc_sub(p, SUB_THREEWAY);
2083                                 if (p->subs[SUB_REAL].inthreeway) {
2084                                         /* This was part of a three way call.  Immediately make way for
2085                                            another call */
2086                                         ast_log(LOG_DEBUG, "Call was complete, setting owner to former third call\n");
2087                                         p->owner = p->subs[SUB_REAL].owner;
2088                                 } else {
2089                                         /* This call hasn't been completed yet...  Set owner to NULL */
2090                                         ast_log(LOG_DEBUG, "Call was incomplete, setting owner to NULL\n");
2091                                         p->owner = NULL;
2092                                 }
2093                                 p->subs[SUB_REAL].inthreeway = 0;
2094                         }
2095                 } else if (index == SUB_CALLWAIT) {
2096                         /* Ditch the holding callwait call, and immediately make it availabe */
2097                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2098                                 /* This is actually part of a three way, placed on hold.  Place the third part
2099                                    on music on hold now */
2100                                 if (p->subs[SUB_THREEWAY].owner && ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2101                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), NULL);
2102                                 p->subs[SUB_THREEWAY].inthreeway = 0;
2103                                 /* Make it the call wait now */
2104                                 swap_subs(p, SUB_CALLWAIT, SUB_THREEWAY);
2105                                 unalloc_sub(p, SUB_THREEWAY);
2106                         } else
2107                                 unalloc_sub(p, SUB_CALLWAIT);
2108                 } else if (index == SUB_THREEWAY) {
2109                         if (p->subs[SUB_CALLWAIT].inthreeway) {
2110                                 /* The other party of the three way call is currently in a call-wait state.
2111                                    Start music on hold for them, and take the main guy out of the third call */
2112                                 if (p->subs[SUB_CALLWAIT].owner && ast_bridged_channel(p->subs[SUB_CALLWAIT].owner))
2113                                         ast_moh_start(ast_bridged_channel(p->subs[SUB_CALLWAIT].owner), NULL);
2114                                 p->subs[SUB_CALLWAIT].inthreeway = 0;
2115                         }
2116                         p->subs[SUB_REAL].inthreeway = 0;
2117                         /* If this was part of a three way call index, let us make
2118                            another three way call */
2119                         unalloc_sub(p, SUB_THREEWAY);
2120                 } else {
2121                         /* This wasn't any sort of call, but how are we an index? */
2122                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
2123                 }
2124         }
2125
2126
2127         if (!p->subs[SUB_REAL].owner && !p->subs[SUB_CALLWAIT].owner && !p->subs[SUB_THREEWAY].owner) {
2128                 p->owner = NULL;
2129                 p->ringt = 0;
2130                 p->distinctivering = 0;
2131                 p->confirmanswer = 0;
2132                 p->cidrings = 1;
2133                 p->outgoing = 0;
2134                 p->digital = 0;
2135                 p->faxhandled = 0;
2136                 p->pulsedial = 0;
2137                 p->onhooktime = time(NULL);
2138 #ifdef ZAPATA_PRI
2139                 p->proceeding = 0;
2140                 p->setup_ack = 0;
2141 #endif          
2142                 if (p->dsp) {
2143                         ast_dsp_free(p->dsp);
2144                         p->dsp = NULL;
2145                 }
2146
2147                 law = ZT_LAW_DEFAULT;
2148                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_SETLAW, &law);
2149                 if (res < 0) 
2150                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
2151                 /* Perform low level hangup if no owner left */
2152 #ifdef ZAPATA_PRI
2153                 if (p->pri) {
2154                         /* Make sure we have a call (or REALLY have a call in the case of a PRI) */
2155                         if (p->call && (!p->bearer || (p->bearer->call == p->call))) {
2156                                 if (!pri_grab(p, p->pri)) {
2157                                         if (p->alreadyhungup) {
2158                                                 ast_log(LOG_DEBUG, "Already hungup...  Calling hangup once, and clearing call\n");
2159                                                 pri_hangup(p->pri->pri, p->call, -1);
2160                                                 p->call = NULL;
2161                                                 if (p->bearer) 
2162                                                         p->bearer->call = NULL;
2163                                         } else {
2164                                                 char *cause = pbx_builtin_getvar_helper(ast,"PRI_CAUSE");
2165                                                 int icause = ast->hangupcause ? ast->hangupcause : -1;
2166                                                 ast_log(LOG_DEBUG, "Not yet hungup...  Calling hangup once with icause, and clearing call\n");
2167                                                 p->alreadyhungup = 1;
2168                                                 if (p->bearer)
2169                                                         p->bearer->alreadyhungup = 1;
2170                                                 if (cause) {
2171                                                         if (atoi(cause))
2172                                                                 icause = atoi(cause);
2173                                                 }
2174                                                 pri_hangup(p->pri->pri, p->call, icause);
2175                                         }
2176                                         if (res < 0) 
2177                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
2178                                         pri_rel(p->pri);                        
2179                                 } else {
2180                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2181                                         res = -1;
2182                                 }
2183                         } else {
2184                                 if (p->bearer)
2185                                         ast_log(LOG_DEBUG, "Bearer call is %p, while ours is still %p\n", p->bearer->call, p->call);
2186                                 p->call = NULL;
2187                                 res = 0;
2188                         }
2189                 }
2190 #endif
2191 #ifdef ZAPATA_R2
2192                 if (p->sig == SIG_R2) {
2193                         if (p->hasr2call) {
2194                                 mfcr2_DropCall(p->r2, NULL, UC_NORMAL_CLEARING);
2195                                 p->hasr2call = 0;
2196                                 res = 0;
2197                         } else
2198                                 res = 0;
2199
2200                 }
2201 #endif
2202                 if (p->sig && (p->sig != SIG_PRI) && (p->sig != SIG_R2))
2203                         res = zt_set_hook(p->subs[SUB_REAL].zfd, ZT_ONHOOK);
2204                 if (res < 0) {
2205                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
2206                 }
2207                 switch(p->sig) {
2208                 case SIG_FXOGS:
2209                 case SIG_FXOLS:
2210                 case SIG_FXOKS:
2211                         res = ioctl(p->subs[SUB_REAL].zfd, ZT_GET_PARAMS, &par);
2212                         if (!res) {
2213 #if 0
2214                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
2215 #endif
2216                                 /* If they're off hook, try playing congestion */
2217                                 if ((par.rxisoffhook) && (!p->radio))
2218                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, ZT_TONE_CONGESTION);
2219                                 else
2220                                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2221                         }
2222                         break;
2223                 case SIG_FXSGS:
2224                 case SIG_FXSLS:
2225                 case SIG_FXSKS:
2226                         /* Make sure we're not made available for at least two seconds assuming
2227                            we were actually used for an inbound or outbound call. */
2228                         if (ast->_state != AST_STATE_RESERVED) {
2229                                 time(&p->guardtime);
2230                                 p->guardtime += 2;
2231                         }
2232                         break;
2233                 default:
2234                         tone_zone_play_tone(p->subs[SUB_REAL].zfd, -1);
2235                 }
2236                 if (p->cidspill)
2237                         free(p->cidspill);
2238                 if (p->sig)
2239                         zt_disable_ec(p);
2240                 x = 0;
2241                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
2242                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
2243                 p->didtdd = 0;
2244                 p->cidspill = NULL;
2245                 p->callwaitcas = 0;
2246                 p->callwaiting = p->permcallwaiting;
2247                 p->hidecallerid = p->permhidecallerid;
2248                 p->dialing = 0;
2249                 p->rdnis[0] = '\0';
2250                 update_conf(p);
2251                 reset_conf(p);
2252                 /* Restore data mode */
2253                 if (p->sig == SIG_PRI) {
2254                         x = 0;
2255                         ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2256                 }
2257 #ifdef ZAPATA_PRI
2258                 if (p->bearer) {
2259                         ast_log(LOG_DEBUG, "Freeing up bearer channel %d\n", p->bearer->channel);
2260                         /* Free up the bearer channel as well, and
2261                            don't use its file descriptor anymore */
2262                         update_conf(p->bearer);
2263                         reset_conf(p->bearer);
2264                         p->bearer->owner = NULL;
2265                         p->bearer->realcall = NULL;
2266                         p->bearer = NULL;
2267                         p->subs[SUB_REAL].zfd = -1;
2268                         p->pri = NULL;
2269                 }
2270 #endif
2271                 restart_monitor();
2272         }
2273
2274
2275         p->callwaitingrepeat = 0;
2276         p->cidcwexpire = 0;
2277         ast->pvt->pvt = NULL;
2278         ast_mutex_unlock(&p->lock);
2279         ast_mutex_lock(&usecnt_lock);
2280         usecnt--;
2281         if (usecnt < 0) 
2282                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
2283         ast_mutex_unlock(&usecnt_lock);
2284         ast_update_use_count();
2285         if (option_verbose > 2) 
2286                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
2287
2288         ast_mutex_lock(&iflock);
2289         tmp = iflist;
2290         prev = NULL;
2291         if (p->destroy) {
2292                 while (tmp) {
2293                         if (tmp == p) {
2294                                 destroy_channel(prev, tmp, 0);
2295                                 break;
2296                         } else {
2297                                 prev = tmp;
2298                                 tmp = tmp->next;
2299                         }
2300                 }
2301         }
2302         ast_mutex_unlock(&iflock);
2303         return 0;
2304 }
2305
2306 static int zt_answer(struct ast_channel *ast)
2307 {
2308         struct zt_pvt *p = ast->pvt->pvt;
2309         int res=0;
2310         int index;
2311         int oldstate = ast->_state;
2312         ast_setstate(ast, AST_STATE_UP);
2313         ast_mutex_lock(&p->lock);
2314         index = zt_get_index(ast, p, 0);
2315         if (index < 0)
2316                 index = SUB_REAL;
2317         /* nothing to do if a radio channel */
2318         if (p->radio) {
2319                 ast_mutex_unlock(&p->lock);
2320                 return 0;
2321         }
2322         switch(p->sig) {
2323         case SIG_FXSLS:
2324         case SIG_FXSGS:
2325         case SIG_FXSKS:
2326                 p->ringt = 0;
2327                 /* Fall through */
2328         case SIG_EM:
2329         case SIG_EM_E1:
2330         case SIG_EMWINK:
2331         case SIG_FEATD:
2332         case SIG_FEATDMF:
2333         case SIG_E911:
2334         case SIG_FEATB:
2335         case SIG_SF:
2336         case SIG_SFWINK:
2337         case SIG_SF_FEATD:
2338         case SIG_SF_FEATDMF:
2339         case SIG_SF_FEATB:
2340         case SIG_FXOLS:
2341         case SIG_FXOGS:
2342         case SIG_FXOKS:
2343                 /* Pick up the line */
2344                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
2345                 if(p->hanguponpolarityswitch) {
2346                         gettimeofday(&p->polaritydelaytv, NULL);
2347                 }
2348                 res =  zt_set_hook(p->subs[SUB_REAL].zfd, ZT_OFFHOOK);
2349                 tone_zone_play_tone(p->subs[index].zfd, -1);
2350                 p->dialing = 0;
2351                 if ((index == SUB_REAL) && p->subs[SUB_THREEWAY].inthreeway) {
2352                         if (oldstate == AST_STATE_RINGING) {
2353                                 ast_log(LOG_DEBUG, "Finally swapping real and threeway\n");
2354                                 tone_zone_play_tone(p->subs[SUB_THREEWAY].zfd, -1);
2355                                 swap_subs(p, SUB_THREEWAY, SUB_REAL);
2356                                 p->owner = p->subs[SUB_REAL].owner;
2357                         }
2358                 }
2359                 if (p->sig & __ZT_SIG_FXS) {
2360                         zt_enable_ec(p);
2361                         zt_train_ec(p);
2362                 }
2363                 break;
2364 #ifdef ZAPATA_PRI
2365         case SIG_PRI:
2366                 /* Send a pri acknowledge */
2367                 if (!pri_grab(p, p->pri)) {
2368                         p->proceeding = 2;
2369                         res = pri_answer(p->pri->pri, p->call, 0, 1);
2370                         pri_rel(p->pri);
2371                 } else {
2372                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
2373                         res= -1;
2374                 }
2375                 break;
2376 #endif
2377 #ifdef ZAPATA_R2
2378         case SIG_R2:
2379                 res = mfcr2_AnswerCall(p->r2, NULL);
2380                 if (res)
2381                         ast_log(LOG_WARNING, "R2 Answer call failed :( on %s\n", ast->name);
2382                 break;
2383 #endif                  
2384         case 0:
2385                 ast_mutex_unlock(&p->lock);
2386                 return 0;
2387         default:
2388                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
2389                 res = -1;
2390         }
2391         ast_mutex_unlock(&p->lock);
2392         return res;
2393 }
2394
2395 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
2396 {
2397 char    *cp;
2398 int     x;
2399
2400         struct zt_pvt *p = chan->pvt->pvt;
2401
2402         
2403         if ((option != AST_OPTION_TONE_VERIFY) && (option != AST_OPTION_AUDIO_MODE) &&
2404                 (option != AST_OPTION_TDD) && (option != AST_OPTION_RELAXDTMF))
2405            {
2406                 errno = ENOSYS;
2407                 return -1;
2408            }
2409         cp = (char *)data;
2410         if ((!cp) || (datalen < 1))
2411            {
2412                 errno = EINVAL;
2413                 return -1;
2414            }
2415         switch(option) {
2416             case AST_OPTION_TONE_VERIFY:
2417                 if (!p->dsp)
2418                         break;
2419                 switch(*cp) {
2420                     case 1:
2421                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
2422                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | p->dtmfrelax);  /* set mute mode if desired */
2423                         break;
2424                     case 2:
2425                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
2426                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_MUTECONF | DSP_DIGITMODE_MUTEMAX | p->dtmfrelax);  /* set mute mode if desired */
2427                         break;
2428                     default:
2429                                 ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
2430                                 ast_dsp_digitmode(p->dsp,DSP_DIGITMODE_DTMF | p->dtmfrelax);  /* set mute mode if desired */
2431                         break;
2432                 }
2433                 break;
2434             case AST_OPTION_TDD:  /* turn on or off TDD */
2435                 if (!*cp) { /* turn it off */
2436                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
2437                         if (p->tdd) tdd_free(p->tdd);
2438                         p->tdd = 0;
2439                         p->mate = 0;
2440                         break;
2441                 }
2442                 if (*cp == 2)
2443                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
2444                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
2445                 p->mate = 0;
2446                 zt_disable_ec(p);
2447                 /* otherwise, turn it on */
2448                 if (!p->didtdd) { /* if havent done it yet */
2449                         unsigned char mybuf[41000],*buf;
2450                         int size,res,fd,len;
2451                         int index;
2452                         struct pollfd fds[1];
2453                         buf = mybuf;
2454                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
2455                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
2456                         len = 40000;
2457                         index = zt_get_index(chan, p, 0);
2458                         if (index < 0) {
2459                                 ast_log(LOG_WARNING, "No index in TDD?\n");
2460                                 return -1;
2461                         }
2462                         fd = p->subs[index].zfd;
2463                         while(len) {
2464                                 if (ast_check_hangup(chan)) return -1;
2465                                 size = len;
2466                                 if (size > READ_SIZE)
2467                                         size = READ_SIZE;
2468                                 fds[0].fd = fd;
2469                                 fds[0].events = POLLPRI | POLLOUT;
2470                                 res = poll(fds, 1, -1);
2471                                 if (!res) {
2472                                         ast_log(LOG_DEBUG, "poll (for write) ret. 0 on channel %d\n", p->channel);
2473                                         continue;
2474                                 }
2475                                   /* if got exception */
2476                                 if (fds[0].revents & POLLPRI) return -1;
2477                                 if (!(fds[0].revents & POLLOUT)) {
2478                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
2479                                         continue;
2480                                 }
2481                                 res = write(fd, buf, size);
2482                                 if (res != size) {
2483                                         if (res == -1) return -1;
2484                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2485                                         break;
2486                                 }
2487                                 len -= size;
2488                                 buf += size;
2489                         }
2490                         p->didtdd = 1; /* set to have done it now */            
2491                 }
2492                 if (*cp == 2) { /* Mate mode */
2493                         if (p->tdd) tdd_free(p->tdd);
2494                         p->tdd = 0;
2495                         p->mate = 1;
2496                         break;
2497                         }               
2498                 if (!p->tdd) { /* if we dont have one yet */
2499                         p->tdd = tdd_new(); /* allocate one */
2500                 }               
2501                 break;
2502             case AST_OPTION_RELAXDTMF:  /* Relax DTMF decoding (or not) */
2503                 if (!*cp)
2504                 {               
2505                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: OFF(0) on %s\n",chan->name);
2506                         x = 0;
2507                 }
2508                 else
2509                 {               
2510                         ast_log(LOG_DEBUG, "Set option RELAX DTMF, value: ON(1) on %s\n",chan->name);
2511                         x = 1;
2512                 }
2513                 ast_dsp_digitmode(p->dsp,x ? DSP_DIGITMODE_RELAXDTMF : DSP_DIGITMODE_DTMF | p->dtmfrelax);
2514                 break;
2515             case AST_OPTION_AUDIO_MODE:  /* Set AUDIO mode (or not) */
2516                 if (!*cp)
2517                 {               
2518                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: OFF(0) on %s\n",chan->name);
2519                         x = 0;
2520                         zt_disable_ec(p);
2521                 }
2522                 else
2523                 {               
2524                         ast_log(LOG_DEBUG, "Set option AUDIO MODE, value: ON(1) on %s\n",chan->name);
2525                         x = 1;
2526                 }
2527                 if (ioctl(p->subs[SUB_REAL].zfd, ZT_AUDIOMODE, &x) == -1)
2528                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d\n", p->channel, x);
2529                 break;
2530         }
2531         errno = 0;
2532         return 0;
2533 }
2534
2535 static void zt_unlink(struct zt_pvt *slave, struct zt_pvt *master, int needlock)
2536 {
2537         /* Unlink a specific slave or all slaves/masters from a given master */
2538         int x;
2539         int hasslaves;
2540         if (!master)
2541                 return;
2542         if (needlock) {
2543                 ast_mutex_lock(&master->lock);
2544                 if (slave) {
2545                         while(ast_mutex_trylock(&slave->lock)) {
2546                                 ast_mutex_unlock(&master->lock);
2547                                 usleep(1);
2548                                 ast_mutex_lock(&master->lock);
2549                         }
2550                 }
2551         }
2552         hasslaves = 0;
2553         for (x=0;x<MAX_SLAVES;x++) {
2554                 if (master->slaves[x]) {
2555                         if (!slave || (master->slaves[x] == slave)) {
2556                                 /* Take slave out of the conference */
2557                                 ast_log(LOG_DEBUG, "Unlinking slave %d from %d\n", master->slaves[x]->channel, master->channel);
2558                                 conf_del(master, &master->slaves[x]->subs[SUB_REAL], SUB_REAL);
2559                                 conf_del(master->slaves[x], &master->subs[SUB_REAL], SUB_REAL);
2560                                 master->slaves[x]->master = NULL;
2561                                 master->slaves[x] = NULL;
2562                         } else
2563                                 hasslaves = 1;
2564                 }
2565                 if (!hasslaves)
2566                         master->inconference = 0;
2567         }
2568         if (!slave) {
2569                 if (master->master) {
2570                         /* Take master out of the conference */
2571                         conf_del(master->master, &master->subs[SUB_REAL], SUB_REAL);
2572                         conf_del(master, &master->master->subs[SUB_REAL], SUB_REAL);
2573                         hasslaves = 0;
2574                         for (x=0;x<MAX_SLAVES;x++) {
2575                                 if (master->master->slaves[x] == master)
2576                                         master->master->slaves[x] = NULL;
2577                                 else if (master->master->slaves[x])
2578                                         hasslaves = 1;
2579                         }
2580                         if (!hasslaves)
2581                                 master->master->inconference = 0;
2582                 }
2583                 master->master = NULL;
2584         }
2585         update_conf(master);
2586         if (needlock) {
2587                 if (slave)
2588                         ast_mutex_unlock(&slave->lock);
2589                 ast_mutex_unlock(&master->lock);
2590         }
2591 }
2592
2593 static void zt_link(struct zt_pvt *slave, struct zt_pvt *master) {
2594         int x;
2595         if (!slave || !master) {
2596                 ast_log(LOG_WARNING, "Tried to link to/from NULL??\n");
2597                 return;
2598         }
2599         for (x=0;x<MAX_SLAVES;x++) {
2600                 if (!master->slaves[x]) {
2601                         master->slaves[x] = slave;
2602                         break;
2603                 }
2604         }
2605         if (x >= MAX_SLAVES) {
2606                 ast_log(LOG_WARNING, "Replacing slave %d with new slave, %d\n", master->slaves[MAX_SLAVES - 1]->channel, slave->channel);
2607                 master->slaves[MAX_SLAVES - 1] = slave;
2608         }
2609         if (slave->master) 
2610                 ast_log(LOG_WARNING, "Replacing master %d with new master, %d\n", slave->master->channel, master->channel);
2611         slave->master = master;
2612         
2613         ast_log(LOG_DEBUG, "Making %d slave to master %d at %d\n", slave->channel, master->channel, x);
2614 }
2615
2616 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
2617 {
2618         struct ast_channel *who = NULL, *cs[3];
2619         struct zt_pvt *p0, *p1, *op0, *op1;
2620         struct zt_pvt *master=NULL, *slave=NULL;
2621         struct ast_frame *f;
2622         int to;
2623         int inconf = 0;
2624         int nothingok = 0;
2625         int ofd1, ofd2;
2626         int oi1, oi2, i1 = -1, i2 = -1, t1, t2;
2627         int os1 = -1, os2 = -1;
2628         struct ast_channel *oc1, *oc2;
2629
2630         /* if need DTMF, cant native bridge */
2631         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
2632                 return -2;
2633                 
2634                 
2635         ast_mutex_lock(&c0->lock);
2636         ast_mutex_lock(&c1->lock);
2637
2638         p0 = c0->pvt->pvt;
2639         p1 = c1->pvt->pvt;
2640         /* cant do pseudo-channels here */
2641         if (!p0 || (!p0->sig) || !p1 || (!p1->sig)) {
2642                 ast_mutex_unlock(&c0->lock);
2643                 ast_mutex_unlock(&c1->lock);
2644                 return -2;
2645         }
2646
2647         op0 = p0 = c0->pvt->pvt;
2648         op1 = p1 = c1->pvt->pvt;
2649         ofd1 = c0->fds[0];
2650         ofd2 = c1->fds[0];
2651         oi1 = zt_get_index(c0, p0, 0);
2652         oi2 = zt_get_index(c1, p1, 0);
2653         oc1 = p0->owner;
2654         oc2 = p1->owner;
2655         if ((oi1 < 0) || (oi2 < 0)) {
2656                 ast_mutex_unlock(&c0->lock);
2657                 ast_mutex_unlock(&c1->lock);
2658                 return -1;
2659         }
2660
2661
2662
2663         ast_mutex_lock(&p0->lock);
2664         if (ast_mutex_trylock(&p1->lock)) {
2665                 /* Don't block, due to potential for deadlock */
2666                 ast_mutex_unlock(&p0->lock);
2667                 ast_mutex_unlock(&c0->lock);
2668                 ast_mutex_unlock(&c1->lock);
2669                 ast_log(LOG_NOTICE, "Avoiding deadlock...\n");
2670                 return -3;
2671         }
2672         if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2673                 if (!p0->owner || !p1->owner) {
2674                         /* Currently unowned -- Do nothing.  */
2675                         nothingok = 1;
2676                 } else {
2677                         /* If we don't have a call-wait in a 3-way, and we aren't in a 3-way, we can be master */
2678                         if (!p0->subs[SUB_CALLWAIT].inthreeway && !p1->subs[SUB_REAL].inthreeway) {
2679                                 master = p0;
2680                                 slave = p1;
2681                                 inconf = 1;
2682                         } else if (!p1->subs[SUB_CALLWAIT].inthreeway && !p0->subs[SUB_REAL].inthreeway) {
2683                                 master = p1;
2684                                 slave = p0;
2685                                 inconf = 1;
2686                         } else {
2687                                 ast_log(LOG_WARNING, "Huh?  Both calls are callwaits or 3-ways?  That's clever...?\n");
2688                                 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,
2689                                                 p0->channel, oi1, (p1->subs[SUB_CALLWAIT].zfd > -1) ? 1 : 0, p1->subs[SUB_REAL].inthreeway);
2690                         }
2691                 }
2692         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_THREEWAY)) {
2693                 if (p1->subs[SUB_THREEWAY].inthreeway) {
2694                         master = p1;
2695                         slave = p0;
2696                 } else {
2697                         nothingok = 1;
2698                 }
2699         } else if ((oi1 == SUB_THREEWAY) && (oi2 == SUB_REAL)) {
2700                 if (p0->subs[SUB_THREEWAY].inthreeway) {
2701                         master = p0;
2702                         slave = p1;
2703                 } else {
2704                         nothingok  = 1;
2705                 }
2706         } else if ((oi1 == SUB_REAL) && (oi2 == SUB_CALLWAIT)) {
2707                 /* We have a real and a call wait.  If we're in a three way call, put us in it, otherwise, 
2708                    don't put us in anything */
2709                 if (p1->subs[SUB_CALLWAIT].inthreeway) {
2710                         master = p1;
2711                         slave = p0;
2712                 } else {
2713                         nothingok = 1;
2714                 }
2715         } else if ((oi1 == SUB_CALLWAIT) && (oi2 == SUB_REAL)) {
2716                 /* Same as previous */
2717                 if (p0->subs[SUB_CALLWAIT].inthreeway) {
2718                         master = p0;
2719                         slave = p1;
2720                 } else {
2721                         nothingok = 1;
2722                 }
2723         }
2724         ast_log(LOG_DEBUG, "master: %d, slave: %d, nothingok: %d\n",
2725                 master ? master->channel : 0, slave ? slave->channel : 0, nothingok);
2726         if (master && slave) {
2727                 /* Stop any tones, or play ringtone as appropriate.  If they're bridged
2728                    in an active threeway call with a channel that is ringing, we should
2729                    indicate ringing. */
2730                 if ((oi2 == SUB_THREEWAY) && 
2731                         p1->subs[SUB_THREEWAY].inthreeway && 
2732                         p1->subs[SUB_REAL].owner && 
2733                         p1->subs[SUB_REAL].inthreeway && 
2734                         (p1->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2735                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c0->name, c1->name);
2736                                 tone_zone_play_tone(p0->subs[oi1].zfd, ZT_TONE_RINGTONE);
2737                                 os2 = p1->subs[SUB_REAL].owner->_state;
2738                 } else {
2739                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p0->channel, oi1, p1->channel, oi2);
2740                                 tone_zone_play_tone(p0->subs[oi1].zfd, -1);
2741                 }
2742                 if ((oi1 == SUB_THREEWAY) && 
2743                         p0->subs[SUB_THREEWAY].inthreeway && 
2744                         p0->subs[SUB_REAL].owner && 
2745                         p0->subs[SUB_REAL].inthreeway && 
2746                         (p0->subs[SUB_REAL].owner->_state == AST_STATE_RINGING)) {
2747                                 ast_log(LOG_DEBUG, "Playing ringback on %s since %s is in a ringing three-way\n", c1->name, c0->name);
2748                                 tone_zone_play_tone(p1->subs[oi2].zfd, ZT_TONE_RINGTONE);
2749                                 os1 = p0->subs[SUB_REAL].owner->_state;
2750                 } else {
2751                                 ast_log(LOG_DEBUG, "Stoping tones on %d/%d talking to %d/%d\n", p1->channel, oi2, p0->channel, oi1);
2752                                 tone_zone_play_tone(p1->subs[oi1].zfd, -1);
2753                 }
2754                 if ((oi1 == SUB_REAL) && (oi2 == SUB_REAL)) {
2755                         if (!p0->echocanbridged || !p1->echocanbridged) {
2756                                 /* Disable echo cancellation if appropriate */
2757                                 zt_disable_ec(p0);
2758                                 zt_disable_ec(p1);
2759                         }
2760                 }
2761                 zt_link(slave, master);
2762                 master->inconference = inconf;
2763         } else if (!nothingok)
2764                 ast_log(LOG_WARNING, "Can't link %d/%s with %d/%s\n", p0->channel, subnames[oi1], p1->channel, subnames[oi2]);
2765
2766         update_conf(p0);
2767         update_conf(p1);
2768         t1 = p0->subs[SUB_REAL].inthreeway;
2769         t2 = p1->subs[SUB_REAL].inthreeway;
2770
2771         ast_mutex_unlock(&p0->lock);
2772         ast_mutex_unlock(&p1->lock);
2773
2774         ast_mutex_unlock(&c0->lock);
2775         ast_mutex_unlock(&c1->lock);
2776
2777         /* Native bridge failed */
2778         if ((!master || !slave) && !nothingok) {
2779                 if (op0 == p0)
2780                         zt_enable_ec(p0);
2781                 if (op1 == p1)
2782                         zt_enable_ec(p1);
2783                 return -1;
2784         }
2785         
2786         cs[0] = c0;
2787         cs[1] = c1;
2788         cs[2] = NULL;
2789         for (;;) {
2790                 /* Here's our main loop...  Start by locking things, looking for private parts, 
2791                    and then balking if anything is wrong */
2792                 ast_mutex_lock(&c0->lock);
2793                 ast_mutex_lock(&c1->lock);
2794                 p0 = c0->pvt->pvt;
2795                 p1 = c1->pvt->pvt;
2796                 if (op0 == p0)
2797                         i1 = zt_get_index(c0, p0, 1);
2798                 if (op1 == p1)
2799                         i2 = zt_get_index(c1, p1, 1);
2800                 ast_mutex_unlock(&c0->lock);
2801                 ast_mutex_unlock(&c1->lock);
2802                 if ((op0 != p0) || (op1 != p1) || 
2803                     (ofd1 != c0->fds[0]) || 
2804                         (ofd2 != c1->fds[0]) ||
2805                     (p0->subs[SUB_REAL].owner && (os1 > -1) && (os1 != p0->subs[SUB_REAL].owner->_state)) || 
2806                     (p1->subs[SUB_REAL].owner && (os2 > -1) && (os2 != p1->subs[SUB_REAL].owner->_state)) || 
2807                     (oc1 != p0->owner) || 
2808                         (oc2 != p1->owner) ||
2809                         (t1 != p0->subs[SUB_REAL].inthreeway) ||
2810                         (t2 != p1->subs[SUB_REAL].inthreeway) ||
2811                         (oi1 != i1) ||
2812                         (oi2 != i2)) {
2813                         if (slave && master)
2814                                 zt_unlink(slave, master, 1);
2815                         ast_log(LOG_DEBUG, "Something changed out on %d/%d to %d/%d, returning -3 to restart\n",
2816                                                                         op0->channel, oi1, op1->channel, oi2);
2817                         if (op0 == p0)
2818                                 zt_enable_ec(p0);
2819                         if (op1 == p1)
2820                                 zt_enable_ec(p1);
2821                         return -3;
2822                 }
2823                 to = -1;
2824                 who = ast_waitfor_n(cs, 2, &to);
2825                 if (!who) {
2826                         ast_log(LOG_DEBUG, "Ooh, empty read...\n");
2827                         continue;
2828                 }
2829                 if (who->pvt->pvt == op0) 
2830                         op0->ignoredtmf = 1;
2831                 else if (who->pvt->pvt == op1)
2832                         op1->ignoredtmf = 1;
2833                 f = ast_read(who);
2834                 if (who->pvt->pvt == op0) 
2835                         op0->ignoredtmf = 0;
2836                 else if (who->pvt->pvt == op1)
2837                         op1->ignoredtmf = 0;
2838                 if (!f) {
2839                         *fo = NULL;
2840                         *rc = who;
2841                         if (slave && master)
2842                                 zt_unlink(slave, master, 1);
2843                         if (op0 == p0)
2844                                 zt_enable_ec(p0);
2845                         if (op1 == p1)
2846                                 zt_enable_ec(p1);
2847                         return 0;
2848                 }
2849                 if (f->frametype == AST_FRAME_CONTROL) {
2850                         *fo = f;
2851                         *rc = who;
2852                         if (slave && master)
2853                                 zt_unlink(slave, master, 1);
2854                         return 0;
2855                 }
2856                 if (f->frametype == AST_FRAME_DTMF) {
2857                         if (((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) || 
2858                             ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1))) {
2859                                 *fo = f;
2860                                 *rc = who;
2861                                 if (slave && master)
2862                                         zt_unlink(slave, master, 1);
2863                                 return 0;
2864                         } else if ((who == c0) && p0->pulsedial) {
2865                                 ast_write(c1, f);
2866                         } else if ((who == c1) && p1->pulsedial) {
2867                                 ast_write(c0, f);
2868                         }
2869                 }
2870                 ast_frfree(f);
2871
2872                 /* Swap who gets priority */
2873                 cs[2] = cs[0];
2874                 cs[0] = cs[1];
2875                 cs[1] = cs[2];
2876         }
2877 }
2878
2879 static int zt_indicate(struct ast_channel *chan, int condition);
2880
2881 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
2882 {
2883         struct zt_pvt *p = newchan->pvt->pvt;
2884         int x;
2885         ast_mutex_lock(&p->lock);
2886         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
2887         if (p->owner == oldchan) {
2888                 p->owner = newchan;
2889         }
2890         for (x=0;x<3;x++)
2891                 if (p->subs[x].owner == oldchan) {
2892                         if (!x)
2893                                 zt_unlink(NULL, p, 0);
2894                         p->subs[x].owner = newchan;
2895                 }
2896         if (newchan->_state == AST_STATE_RINGING) 
2897                 zt_indicate(newchan, AST_CONTROL_RINGING);
2898         update_conf(p);
2899         ast_mutex_unlock(&p->lock);
2900         return 0;
2901 }
2902
2903 static int zt_ring_phone(struct zt_pvt *p)
2904 {
2905         int x;
2906         int res;
2907         /* Make sure our transmit state is on hook */
2908         x = 0;
2909         x = ZT_ONHOOK;
2910         res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2911         do {
2912                 x = ZT_RING;
2913                 res = ioctl(p->subs[SUB_REAL].zfd, ZT_HOOK, &x);
2914 #if 0
2915                 printf("Res: %d, error: %s\n", res, strerror(errno));
2916 #endif                                          
2917                 if (res) {
2918                         switch(errno) {
2919                         case EBUSY:
2920                         case EINTR:
2921                                 /* Wait just in case */
2922                                 usleep(10000);
2923                                 continue;
2924                         case EINPROGRESS:
2925                                 res = 0;
2926                                 break;
2927                         default:
2928                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
2929                                 res = 0;
2930                         }
2931                 }
2932         } while (res);
2933         return res;
2934 }
2935
2936 static void *ss_thread(void *data);
2937
2938 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int, int);
2939
2940 static int attempt_transfer(struct zt_pvt *p)
2941 {
2942         /* In order to transfer, we need at least one of the channels to
2943            actually be in a call bridge.  We can't conference two applications
2944            together (but then, why would we want to?) */
2945         if (ast_bridged_channel(p->subs[SUB_REAL].owner)) {
2946                 /* The three-way person we're about to transfer to could still be in MOH, so
2947                    stop if now if appropriate */
2948                 if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner))
2949                         ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
2950                 if (p->subs[SUB_THREEWAY].owner->_state == AST_STATE_RINGING) {
2951                         ast_indicate(ast_bridged_channel(p->subs[SUB_REAL].owner), AST_CONTROL_RINGING);
2952                 }
2953                 if (p->subs[SUB_REAL].owner->cdr) {
2954                         /* Move CDR from second channel to current one */
2955                         p->subs[SUB_THREEWAY].owner->cdr =
2956                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, p->subs[SUB_REAL].owner->cdr);
2957                         p->subs[SUB_REAL].owner->cdr = NULL;
2958                 }
2959                 if (ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr) {
2960                         /* Move CDR from second channel's bridge to current one */
2961                         p->subs[SUB_THREEWAY].owner->cdr =
2962                                 ast_cdr_append(p->subs[SUB_THREEWAY].owner->cdr, ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr);
2963                         ast_bridged_channel(p->subs[SUB_REAL].owner)->cdr = NULL;
2964                 }
2965                  if (ast_channel_masquerade(p->subs[SUB_THREEWAY].owner, ast_bridged_channel(p->subs[SUB_REAL].owner))) {
2966                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
2967                                         ast_bridged_channel(p->subs[SUB_REAL].owner)->name, p->subs[SUB_THREEWAY].owner->name);
2968                         return -1;
2969                 }
2970                 /* Orphan the channel after releasing the lock */
2971                 ast_mutex_unlock(&p->subs[SUB_THREEWAY].owner->lock);
2972                 unalloc_sub(p, SUB_THREEWAY);
2973         } else if (ast_bridged_channel(p->subs[SUB_THREEWAY].owner)) {
2974                 if (p->subs[SUB_REAL].owner->_state == AST_STATE_RINGING) {
2975                         ast_indicate(ast_bridged_channel(p->subs[SUB_THREEWAY].owner), AST_CONTROL_RINGING);
2976                 }
2977                 ast_moh_stop(ast_bridged_channel(p->subs[SUB_THREEWAY].owner));
2978                 if (p->subs[SUB_THREEWAY].owner->cdr) {
2979                         /* Move CDR from second channel to current one */
2980                         p->subs[SUB_REAL].owner->cdr = 
2981                                 ast_cdr_append(p->subs[SUB_REAL].owner->cdr, p->subs[SUB_THREEWAY].owner->cdr);