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