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