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