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