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