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