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