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