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