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