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