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