Version 0.3.0 from FTP
[asterisk/asterisk.git] / channels / chan_zap.c
1 /*
2  * Asterisk -- A telephony toolkit for Linux.
3  *
4  * Tormenta T1 Card (via Zapata library) support 
5  * 
6  * Copyright (C) 1999, Mark Spencer
7  *
8  * Mark Spencer <markster@linux-support.net>
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/callerid.h>
27 #include <asterisk/adsi.h>
28 #include <asterisk/cli.h>
29 #include <asterisk/cdr.h>
30 #include <asterisk/parking.h>
31 #include <asterisk/musiconhold.h>
32 #include <asterisk/tdd.h>
33 #include <sys/signal.h>
34 #include <sys/select.h>
35 #include <errno.h>
36 #include <stdlib.h>
37 #include <unistd.h>
38 #include <sys/ioctl.h>
39 #include <linux/zaptel.h>
40 #include <zap.h>
41 #include <math.h>
42 #include <tonezone.h>
43 #include <dirent.h>
44 #ifdef ZAPATA_PRI
45 #include <libpri.h>
46 #endif
47
48 #include "../asterisk.h"
49
50 /* 
51    XXX 
52    XXX   We definitely need to lock the private structure in zt_read and such 
53    XXX  
54  */
55
56 #define RINGT 274
57
58 /*
59  * Define ZHONE_HACK to cause us to go off hook and then back on hook when
60  * the user hangs up to reset the state machine so ring works properly.
61  * This is used to be able to support kewlstart by putting the zhone in
62  * groundstart mode since their forward disconnect supervision is entirely
63  * broken even though their documentation says it isn't and their support
64  * is entirely unwilling to provide any assistance with their channel banks
65  * even though their web site says they support their products for life.
66  */
67
68 #define ZHONE_HACK
69
70 #define CHANNEL_PSEUDO -12
71
72 #ifdef ZAPATA_PRI
73 static char *desc = "Zapata Telephony (PRI) Driver";
74 static char *tdesc = "Zapata Telephony + PRI Interface Driver";
75 #else
76 static char *desc = "Zapata Telphony Driver";
77 static char *tdesc = "Zapata Telephony Interface Driver";
78 #endif
79 static char *type = "Zap";
80 static char *typecompat = "Tor";        /* Retain compatibility with chan_tor */
81 static char *config = "zapata.conf";
82
83 #define SIG_EM          ZT_SIG_EM
84 #define SIG_EMWINK      (0x10000 | ZT_SIG_EM)
85 #define SIG_FEATD       (0x20000 | ZT_SIG_EM)
86 #define SIG_FEATDMF     (0x40000 | ZT_SIG_EM)
87 #define SIG_FEATB       (0x80000 | ZT_SIG_EM)
88 #define SIG_FXSLS       ZT_SIG_FXSLS
89 #define SIG_FXSGS       ZT_SIG_FXSGS
90 #define SIG_FXSKS       ZT_SIG_FXSKS
91 #define SIG_FXOLS       ZT_SIG_FXOLS
92 #define SIG_FXOGS       ZT_SIG_FXOGS
93 #define SIG_FXOKS       ZT_SIG_FXOKS
94 #define SIG_PRI         ZT_SIG_CLEAR
95
96 #define NUM_SPANS       32
97 #define RESET_INTERVAL  3600    /* How often (in seconds) to reset unused channels */
98
99 #define CHAN_PSEUDO     -2
100
101 static char context[AST_MAX_EXTENSION] = "default";
102 static char callerid[256] = "";
103
104 static char language[MAX_LANGUAGE] = "";
105 static char musicclass[MAX_LANGUAGE] = "";
106
107 static int use_callerid = 1;
108
109 static int cur_signalling = -1;
110
111 static int cur_group = 0;
112 static int cur_callergroup = 0;
113 static int cur_pickupgroup = 0;
114
115 static int immediate = 0;
116
117 static int stripmsd = 0;
118
119 static int callwaiting = 0;
120
121 static int callwaitingcallerid = 0;
122
123 static int hidecallerid = 0;
124
125 static int threewaycalling = 0;
126
127 static int transfer = 0;
128
129 static int cancallforward = 0;
130
131 static float rxgain = 0.0;
132
133 static float txgain = 0.0;
134
135 static int echocancel;
136
137 static int echocanbridged = 0;
138
139 static char accountcode[20] = "";
140
141 static char mailbox[AST_MAX_EXTENSION];
142
143 static int amaflags = 0;
144
145 static int adsi = 0;
146
147 #ifdef ZAPATA_PRI
148 static int minunused = 2;
149 static int minidle = 0;
150 static char idleext[AST_MAX_EXTENSION];
151 static char idledial[AST_MAX_EXTENSION];
152 #endif
153
154 /* Wait up to 16 seconds for first digit (FXO logic) */
155 static int firstdigittimeout = 16000;
156
157 /* How long to wait for following digits (FXO logic) */
158 static int gendigittimeout = 8000;
159
160 static int usecnt =0;
161 static pthread_mutex_t usecnt_lock = AST_MUTEX_INITIALIZER;
162
163 /* Protect the interface list (of zt_pvt's) */
164 static pthread_mutex_t iflock = AST_MUTEX_INITIALIZER;
165
166 /* Protect the monitoring thread, so only one process can kill or start it, and not
167    when it's doing something critical. */
168 static pthread_mutex_t monlock = AST_MUTEX_INITIALIZER;
169
170 /* This is the thread for the monitor which checks for input on the channels
171    which are not currently in use.  */
172 static pthread_t monitor_thread = 0;
173
174 static int restart_monitor(void);
175
176 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc);
177
178 static int zt_sendtext(struct ast_channel *c, char *text);
179
180 static inline int zt_get_event(int fd)
181 {
182         /* Avoid the silly zt_getevent which ignores a bunch of events */
183         int j;
184         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
185         return j;
186 }
187
188 static inline int zt_wait_event(int fd)
189 {
190         /* Avoid the silly zt_waitevent which ignores a bunch of events */
191         int i,j=0;
192         i = ZT_IOMUX_SIGEVENT;
193         if (ioctl(fd, ZT_IOMUX, &i) == -1) return -1;
194         if (ioctl(fd, ZT_GETEVENT, &j) == -1) return -1;
195         return j;
196 }
197
198 /* Chunk size to read -- we use the same size as the chunks that the zapata library uses.  */   
199 #define READ_SIZE 204
200
201 #define MASK_AVAIL              (1 << 0)                /* Channel available for PRI use */
202 #define MASK_INUSE              (1 << 1)                /* Channel currently in use */
203
204 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /* 300 ms */
205 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /* 300 ms */
206
207 struct zt_pvt;
208
209
210 #ifdef ZAPATA_PRI
211 struct zt_pri {
212         pthread_t master;                       /* Thread of master */
213         pthread_mutex_t lock;           /* Mutex */
214         char idleext[AST_MAX_EXTENSION];                /* Where to idle extra calls */
215         char idlecontext[AST_MAX_EXTENSION];            /* What context to use for idle */
216         char idledial[AST_MAX_EXTENSION];               /* What to dial before dumping */
217         int minunused;                          /* Min # of channels to keep empty */
218         int minidle;                            /* Min # of "idling" calls to keep active */
219         int nodetype;                           /* Node type */
220         int switchtype;                         /* Type of switch to emulate */
221         int dchannel;                   /* What channel the dchannel is on */
222         int channels;                   /* Num of chans in span (31 or 24) */
223         struct pri *pri;
224         int debug;
225         int fd;
226         int up;
227         int offset;
228         int span;
229         int chanmask[31];                       /* Channel status */
230         int resetting;
231         int resetchannel;
232         time_t lastreset;
233         struct zt_pvt *pvt[31]; /* Member channel pvt structs */
234         struct zt_channel *chan[31];    /* Channels on each line */
235 };
236
237
238 static struct zt_pri pris[NUM_SPANS];
239
240 static int pritype = PRI_CPE;
241
242 #if 0
243 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
244 #else
245 #define DEFAULT_PRI_DEBUG 0
246 #endif
247
248 static inline int pri_grab(struct zt_pri *pri)
249 {
250         int res;
251         /* Grab the lock first */
252     res = ast_pthread_mutex_lock(&pri->lock);
253         if (res)
254                 return res;
255         /* Then break the select */
256         pthread_kill(pri->master, SIGURG);
257         return 0;
258 }
259
260 static inline void pri_rel(struct zt_pri *pri)
261 {
262         ast_pthread_mutex_unlock(&pri->lock);
263 }
264
265 static int switchtype = PRI_SWITCH_NI2;
266
267 #endif
268
269 static struct zt_pvt {
270         ZAP *z;
271         pthread_mutex_t lock;
272         struct ast_channel *owner;      /* Our owner (if applicable) */
273         struct ast_channel *owners[3];  
274                 /* Up to three channels can be associated with this call */
275                 
276         int callwaitindex;                      /* Call waiting index into owners */    
277         int thirdcallindex;                     /* Three-way calling index into owners */
278         int normalindex;                        /* "Normal" call index into owners */
279         
280         int sig;                                        /* Signalling style */
281         float rxgain;
282         float txgain;
283         struct zt_pvt *next;                    /* Next channel in list */
284         char context[AST_MAX_EXTENSION];
285         char exten[AST_MAX_EXTENSION];
286         char language[MAX_LANGUAGE];
287         char musicclass[MAX_LANGUAGE];
288         char callerid[AST_MAX_EXTENSION];
289         char callwaitcid[AST_MAX_EXTENSION];
290         char dtmfq[AST_MAX_EXTENSION];
291         struct ast_frame f_unused;      /* Usually unused, but could in rare cases be needed */
292         struct ast_frame f[3];          /* One frame for each channel.  How did this ever work before? */
293         short buffer[3][AST_FRIENDLY_OFFSET/2 + READ_SIZE];
294         int group;
295         int law;
296         int callgroup;
297         int pickupgroup;
298         int immediate;                          /* Answer before getting digits? */
299         int channel;                            /* Channel Number */
300         int span;                                       /* Span number */
301         int dialing;
302         int dialednone;
303         int use_callerid;                       /* Whether or not to use caller id on this channel */
304         int hidecallerid;
305         int permhidecallerid;           /* Whether to hide our outgoing caller ID or not */
306         int callwaitingrepeat;          /* How many samples to wait before repeating call waiting */
307         unsigned char *cidspill;
308         int cidpos;
309         int cidlen;
310         int ringt;
311         int stripmsd;
312         int needringing[3];
313         int needanswer[3];
314         int callwaiting;
315         int callwaitcas;
316         int callwaitrings;
317         int echocancel;
318         int echocanbridged;
319         int permcallwaiting;
320         int callwaitingcallerid;
321         int threewaycalling;
322         int transfer;
323         int dnd;
324         int cref;                                       /* Call reference number */
325         ZT_DIAL_OPERATION dop;
326         struct zt_confinfo conf;        /* Saved state of conference */
327         struct zt_confinfo conf2;       /* Saved state of alternate conference */
328         int confno;                                     /* Conference number */
329         ZAP *pseudo;                            /* Pseudo channel FD */
330         int pseudochan;                         /* Pseudo channel */
331         int destroy;
332         int ignoredtmf;                         
333         int inalarm;
334         char accountcode[20];           /* Account code */
335         int amaflags;                           /* AMA Flags */
336         char didtdd;                    /* flag to say its done it once */
337         struct tdd_state *tdd;          /* TDD flag */
338         int reallinear;
339         int pseudolinear;
340         int adsi;
341         int cancallforward;
342         char call_forward[AST_MAX_EXTENSION];
343         char mailbox[AST_MAX_EXTENSION];
344         
345         int confirmanswer;              /* Wait for '#' to confirm answer */
346         int distinctivering;    /* Which distinctivering to use */
347         int cidrings;                   /* Which ring to deliver CID on */
348         
349         char mate;                      /* flag to say its in MATE mode */
350 #ifdef ZAPATA_PRI
351         struct zt_pri *pri;
352         q931_call *call;
353         int isidlecall;
354         int resetting;
355 #endif  
356 } *iflist = NULL;
357
358 static struct zt_ring_cadence cadences[] = {
359         { { 125, 125, 2000, 4000 } },                   /* Quick chirp followed by normal ring */
360         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /* British style ring */
361         { { 125, 125, 125, 125, 125, 4000 } },  /* Three short bursts */
362         { { 1000, 500, 2500, 5000 } },  /* Long ring */
363 };
364
365 static int cidrings[] = {
366         2,                                                                              /* Right after first long ring */
367         4,                                                                              /* Right after long part */
368         3,                                                                              /* After third chirp */
369         2,                                                                              /* Second spell */
370 };
371
372 #define NUM_CADENCE (sizeof(cadences) / sizeof(cadences[0]))
373
374 #define INTHREEWAY(p) ((p->normalindex > -1) && (p->thirdcallindex > -1) && \
375                 (p->owner == p->owners[p->normalindex]))
376
377 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
378                         (p->sig == SIG_FXSGS))
379
380
381 /* return non-zero if clear dtmf is appropriate */
382 static int CLEARDTMF(struct ast_channel *chan) {
383 struct zt_pvt *p = chan->pvt->pvt,*themp;
384 struct ast_channel *them;
385         if (!p)
386                 return 0;
387           /* if not in a 3 way, we should be okay */
388         if (p->thirdcallindex == -1) return 1;
389           /* get the other side of the call's channel pointer */
390         if (p->owners[p->normalindex] == chan)
391                 them = p->owners[p->thirdcallindex];
392         else
393                 them = p->owners[p->normalindex];
394         if (!them)
395                 return 0;
396         if (!them->bridge) return 1;
397           /* get their private structure, too */
398         themp = them->pvt->pvt;
399           /* if does not use zt bridge code, return 0 */
400         if (them->pvt->bridge != zt_bridge) return 0;
401         if (them->bridge->pvt->bridge != zt_bridge) return 0;
402         return 1; /* okay, I guess we are okay to be clear */
403 }
404
405 static int alloc_pseudo(struct zt_pvt *p)
406 {
407         int x;
408         ZAP *z;
409         int res;
410         ZT_BUFFERINFO bi;
411         if (p->pseudo || p->pseudochan){
412                 ast_log(LOG_WARNING, "Already have a pseudo fd: %d, chan: %d\n",
413                         zap_fd(p->pseudo), p->pseudochan);
414                 return -1;
415         }
416         z = zap_open("/dev/zap/pseudo", 1);
417         if (!z) {
418                 ast_log(LOG_WARNING, "Unable to open /dev/zap/pseudo: %s\n", strerror(errno));
419                 return -1;
420         } else {
421                 res = ioctl(zap_fd(z), ZT_GET_BUFINFO, &bi);
422                 if (!res) {
423                         bi.txbufpolicy = ZT_POLICY_IMMEDIATE;
424                         bi.rxbufpolicy = ZT_POLICY_IMMEDIATE;
425                         bi.numbufs = 4;
426                         res = ioctl(zap_fd(z), ZT_SET_BUFINFO, &bi);
427                         if (res < 0) {
428                                 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
429                         }
430                 } else 
431                         ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
432                 p->pseudo = z;
433                 if (ioctl(zap_fd(z), ZT_CHANNO, &x) == 1) {
434                         ast_log(LOG_WARNING,"Unable to get channel number for pseudo channel on FD %d\n",zap_fd(z));
435                         return -1;
436                 }
437                 p->pseudochan = x;
438                 if (option_debug)
439                         ast_log(LOG_DEBUG, "Allocated pseudo channel %d on FD %d\n", p->pseudochan, zap_fd(p->pseudo));
440                 return 0;
441         }
442         /* Never reached */
443         return 0;
444 }
445
446 static int unalloc_pseudo(struct zt_pvt *p)
447 {
448         if (p->pseudo)
449                 zap_close(p->pseudo);
450         if (option_debug)
451                 ast_log(LOG_DEBUG, "Released pseudo channel %d\n", p->pseudochan);
452         p->pseudolinear = 0;
453         p->pseudo = NULL;
454         p->pseudochan = 0;
455         return 0;
456 }
457
458 static int zt_digit(struct ast_channel *ast, char digit)
459 {
460         ZT_DIAL_OPERATION zo;
461         struct zt_pvt *p;
462         int res;
463         zo.op = ZT_DIAL_OP_APPEND;
464         zo.dialstr[0] = 'T';
465         zo.dialstr[1] = digit;
466         zo.dialstr[2] = 0;
467         p = ast->pvt->pvt;
468         if ((res = ioctl(zap_fd(p->z), ZT_DIAL, &zo)))
469                 ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
470         else
471                 p->dialing = 1;
472         
473         return res;
474 }
475
476 static char *events[] = {
477         "No event",
478         "On hook",
479         "Ring/Answered",
480         "Wink/Flash",
481         "Alarm",
482         "No more alarm",
483                 "HDLC Abort",
484                 "HDLC Overrun",
485                 "HDLC Bad FCS",
486                 "Dial Complete",
487                 "Ringer On",
488                 "Ringer Off",
489                 "Hook Transition Complete"
490 };
491  
492 static char *event2str(int event)
493 {
494         static char buf[256];
495         if ((event < 13) && (event > -1))
496                 return events[event];
497         sprintf(buf, "Event %d", event);
498         return buf;
499 }
500
501 static char *sig2str(int sig)
502 {
503         static char buf[256];
504         switch(sig) {
505         case SIG_EM:
506                 return "E & M Immediate";
507         case SIG_EMWINK:
508                 return "E & M Wink";
509         case SIG_FEATD:
510                 return "Feature Group D (DTMF)";
511         case SIG_FEATDMF:
512                 return "Feature Group D (MF)";
513         case SIG_FEATB:
514                 return "Feature Group B (MF)";
515         case SIG_FXSLS:
516                 return "FXS Loopstart";
517         case SIG_FXSGS:
518                 return "FXS Groundstart";
519         case SIG_FXSKS:
520                 return "FXS Kewlstart";
521         case SIG_FXOLS:
522                 return "FXO Loopstart";
523         case SIG_FXOGS:
524                 return "FXO Groundstart";
525         case SIG_FXOKS:
526                 return "FXO Kewlstart";
527         case SIG_PRI:
528                 return "PRI Signalling";
529         case 0:
530                 return "Pseudo Signalling";
531         default:
532                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
533                 return buf;
534         }
535 }
536
537 static int conf_set(struct zt_pvt *p, int req, int force)
538 {
539
540         /* Set channel to given conference, -1 to allocate one */
541         ZT_CONFINFO ci;
542         ZT_CONFINFO cip;
543         int res;
544         if ((p->confno > -1) && (p->confno != req) && (!force)) {
545                 ast_log(LOG_WARNING, "Channel %d already has conference %d allocated\n", p->channel, p->confno);
546                 return -1;
547         }
548         ci.chan = 0;
549         ci.confno = 0;
550         /* Check current conference stuff */
551         res = ioctl(zap_fd(p->z), ZT_GETCONF, &ci);
552         if (res < 0) {
553                 ast_log(LOG_WARNING, "Failed to get conference info on channel %d: %s\n",
554                         p->channel, strerror(errno));
555                 return -1;
556         }
557         if (!force && ci.confmode && (ci.confno != p->confno)) {
558                 ast_log(LOG_WARNING, "Channel %d is already in a conference (%d, %x) we didn't create (though we did make %d) (req = %d)\n", p->channel, ci.confno, ci.confmode, p->confno, req);
559                 return -1;
560         }
561         ci.chan = 0;
562         ci.confno = req;
563         ci.confmode = ZT_CONF_REALANDPSEUDO | ZT_CONF_TALKER | ZT_CONF_LISTENER | ZT_CONF_PSEUDO_LISTENER | ZT_CONF_PSEUDO_TALKER; 
564         res = ioctl(zap_fd(p->z), ZT_SETCONF, &ci);
565         if (res < 0) {
566                 ast_log(LOG_WARNING, "Failed to set conference to %d on channel %d: %s\n",
567                         req, p->channel, strerror(errno));
568                 return -1;
569         }
570         if (INTHREEWAY(p)) {
571                         /* We have a three way call active, be sure the third participant is included in
572                            our conference. */
573                 cip.chan = 0;
574                 cip.confno = ci.confno;
575                 cip.confmode = ZT_CONF_CONF | ZT_CONF_TALKER | ZT_CONF_LISTENER;
576                 
577                 res = ioctl(zap_fd(p->pseudo), ZT_SETCONF, &cip);
578                 if (res < 0) {
579                         ast_log(LOG_WARNING, "Failed to set conference info on pseudo channel %d: %s\n",
580                                 p->pseudochan, strerror(errno));
581                         return -1;
582                 }
583                 ast_log(LOG_DEBUG, "Conferenced in third way call\n");
584         } else {
585                 if (p->pseudo || (p->pseudochan)) {
586                         ast_log(LOG_DEBUG, "There's a pseudo something on %d (channel %d), but we're not conferencing it in at the moment?\n",
587                                 zap_fd(p->pseudo), p->pseudochan);
588                         cip.chan = 0;
589                         cip.confno = 0;
590                         cip.confmode = ZT_CONF_NORMAL;
591                         res = ioctl(zap_fd(p->pseudo), ZT_SETCONF, &cip);
592                         if (res < 0) {
593                                 ast_log(LOG_WARNING, "Failed to set conference info on pseudo channel %d (mode %08x, conf %d): %s\n",
594                                         p->pseudochan, cip.confno, cip.confmode, strerror(errno));
595                                 return -1;
596                         }
597                 }
598         }
599         p->confno = ci.confno;
600         return 0;
601 }
602
603 static int three_way(struct zt_pvt *p)
604 {
605         ast_log(LOG_DEBUG, "Setting up three way call\n");
606         return conf_set(p, p->confno, 0);
607 }
608
609 static int conf_clear(struct zt_pvt *p)
610 {
611         ZT_CONFINFO ci;
612         int res;
613         ci.confmode = ZT_CONF_NORMAL;
614         ci.chan = 0;
615         ci.confno = 0;
616         res = ioctl(zap_fd(p->z), ZT_SETCONF, &ci);
617         if (res < 0) {
618                 ast_log(LOG_WARNING, "Failed to clear conference info on channel %d: %s\n",
619                         p->channel, strerror(errno));
620                 return -1;
621         }
622         p->confno = -1;
623         return 0;
624 }
625
626 static void zt_enable_ec(struct zt_pvt *p)
627 {
628         int x;
629         int res;
630         if (p && p->echocancel) {
631                 x = p->echocancel;
632                 res = ioctl(zap_fd(p->z), ZT_ECHOCANCEL, &x);
633                 if (res) 
634                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d\n", p->channel);
635                 else
636                         ast_log(LOG_DEBUG, "Enabled echo cancellation on channel %d\n", p->channel);
637         } else
638                 ast_log(LOG_DEBUG, "No echocancellation requested\n");
639 }
640
641 static void zt_disable_ec(struct zt_pvt *p)
642 {
643         int x;
644         int res;
645         if (p->echocancel) {
646                 x = 0;
647                 res = ioctl(zap_fd(p->z), ZT_ECHOCANCEL, &x);
648                 if (res) 
649                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
650                 else
651                         ast_log(LOG_DEBUG, "disabled echo cancellation on channel %d\n", p->channel);
652         }
653 }
654
655 static int zt_get_index(struct ast_channel *ast, struct zt_pvt *p, int nullok)
656 {
657         int res;
658         if (p->owners[0] == ast)
659                 res = 0;
660         else if (p->owners[1] == ast)
661                 res = 1;
662         else if (p->owners[2] == ast)
663                 res = 2;
664         else {
665                 res = -1;
666                 if (!nullok)
667                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
668         }
669         return res;
670 }
671
672 int set_actual_gain(int fd, int chan, float rxgain, float txgain)
673 {
674         struct  zt_gains g;
675         float ltxgain;
676         float lrxgain;
677         int j,k;
678         g.chan = chan;
679           /* caluculate linear value of tx gain */
680         ltxgain = pow(10.0,txgain / 20.0);
681           /* caluculate linear value of rx gain */
682         lrxgain = pow(10.0,rxgain / 20.0);
683         for (j=0;j<256;j++) {
684                 /* XXX Fix for A-law XXX */
685                 k = (int)(((float)AST_MULAW(j)) * lrxgain);
686                 if (k > 32767) k = 32767;
687                 if (k < -32767) k = -32767;
688                 g.rxgain[j] = AST_LIN2MU(k);
689                 k = (int)(((float)AST_MULAW(j)) * ltxgain);
690                 if (k > 32767) k = 32767;
691                 if (k < -32767) k = -32767;
692                 g.txgain[j] = AST_LIN2MU(k);
693         }
694                 
695           /* set 'em */
696         return(ioctl(fd,ZT_SETGAINS,&g));
697 }
698
699 static inline int zt_set_hook(int fd, int hs)
700 {
701         int x, res;
702         x = hs;
703         res = ioctl(fd, ZT_HOOK, &x);
704         if (res < 0) 
705                 ast_log(LOG_WARNING, "zt hook failed: %s\n", strerror(errno));
706         return res;
707 }
708
709 static int save_conference(struct zt_pvt *p)
710 {
711         struct zt_confinfo c;
712         int res;
713         if (p->conf.confmode) {
714                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
715                 return -1;
716         }
717         p->conf.chan = 0;
718         res = ioctl(zap_fd(p->z), ZT_GETCONF, &p->conf);
719         if (res) {
720                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
721                 p->conf.confmode = 0;
722                 return -1;
723         }
724         c.chan = 0;
725         c.confno = 0;
726         c.confmode = ZT_CONF_NORMAL;
727         res = ioctl(zap_fd(p->z), ZT_SETCONF, &c);
728         if (res) {
729                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
730                 return -1;
731         }
732         switch(p->conf.confmode) {
733         case ZT_CONF_NORMAL:
734                 p->conf2.confmode = 0;
735                 break;
736         case ZT_CONF_MONITOR:
737                 /* Get the other size */
738                 p->conf2.chan = p->conf.confno;
739                 res = ioctl(zap_fd(p->z), ZT_GETCONF, &p->conf2);
740                 if (res) {
741                         ast_log(LOG_WARNING, "Unable to get secondaryconference info: %s\n", strerror(errno));
742                         p->conf2.confmode = 0;
743                         return -1;
744                 }
745                 c.chan = p->conf.confno;
746                 c.confno = 0;
747                 c.confmode = ZT_CONF_NORMAL;
748                 res = ioctl(zap_fd(p->z), ZT_SETCONF, &c);
749                 if (res) {
750                         ast_log(LOG_WARNING, "Unable to set secondaryconference info: %s\n", strerror(errno));
751                         p->conf2.confmode = 0;
752                         return -1;
753                 }
754                 break;
755         case ZT_CONF_CONF | ZT_CONF_LISTENER | ZT_CONF_TALKER:
756                 p->conf2.confmode = 0;
757                 break;
758         default:
759                 ast_log(LOG_WARNING, "Don't know how to save conference state for conf mode %08x\n", p->conf.confmode);
760                 return -1;
761         }
762         if (option_debug)
763                 ast_log(LOG_DEBUG, "Disabled conferencing\n");
764         return 0;
765 }
766
767 static int restore_conference(struct zt_pvt *p)
768 {
769         int res;
770         if (p->conf.confmode) {
771                 res = ioctl(zap_fd(p->z), ZT_SETCONF, &p->conf);
772                 p->conf.confmode = 0;
773                 if (res) {
774                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
775                         return -1;
776                 }
777                 if (p->conf2.confmode) {
778                         res = ioctl(zap_fd(p->z), ZT_SETCONF, &p->conf2);
779                         p->conf2.confmode = 0;
780                         if (res) {
781                                 ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
782                                 return -1;
783                         }
784                 }
785         }
786         if (option_debug)
787                 ast_log(LOG_DEBUG, "Restored conferencing\n");
788         return 0;
789 }
790
791 static int send_callerid(struct zt_pvt *p);
792
793 int send_cwcidspill(struct zt_pvt *p)
794 {
795         p->callwaitcas = 0;
796         p->cidspill = malloc(MAX_CALLERID_SIZE);
797         if (p->cidspill) {
798                 memset(p->cidspill, 0x7f, MAX_CALLERID_SIZE);
799                 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwaitcid);
800                 /* Make sure we account for the end */
801                 p->cidlen += READ_SIZE * 4;
802                 p->cidpos = 0;
803                 send_callerid(p);
804                 if (option_verbose > 2)
805                         ast_verbose(VERBOSE_PREFIX_3 "CPE supports Call Waiting Caller*ID.  Sending '%s'\n", p->callwaitcid);
806         } else return -1;
807         return 0;
808 }
809
810 static int has_voicemail(struct zt_pvt *p)
811 {
812         DIR *dir;
813         struct dirent *de;
814         char fn[256];
815
816         /* If no mailbox, return immediately */
817         if (!strlen(p->mailbox))
818                 return 0;
819         snprintf(fn, sizeof(fn), "%s/vm/%s/INBOX", AST_SPOOL_DIR, p->mailbox);
820         dir = opendir(fn);
821         if (!dir)
822                 return 0;
823         while ((de = readdir(dir))) {
824                 if (!strncasecmp(de->d_name, "msg", 3))
825                         break;
826         }
827         closedir(dir);
828         if (de)
829                 return 1;
830         return 0;
831 }
832
833 static int send_callerid(struct zt_pvt *p)
834 {
835         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
836         int res;
837         while(p->cidpos < p->cidlen) {
838                 res = write(zap_fd(p->z), p->cidspill + p->cidpos, p->cidlen - p->cidpos);
839                 if (res < 0) {
840                         if (errno == EAGAIN)
841                                 return 0;
842                         else {
843                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
844                                 return -1;
845                         }
846                 }
847                 if (!res)
848                         return 0;
849                 p->cidpos += res;
850         }
851         free(p->cidspill);
852         p->cidspill = 0;
853         if (p->callwaitcas) {
854                 zap_clrdtmfn(p->z);
855                 /* Check for a the ack on the CAS (up to 500 ms) */
856                 res = zap_getdtmf(p->z, 1, NULL, 0, 500, 500, ZAP_HOOKEXIT | ZAP_TIMEOUTOK);
857                 if (res > 0) {
858                         char tmp[2];
859                         strncpy(tmp, zap_dtmfbuf(p->z), sizeof(tmp)-1);
860                         zap_clrdtmfn(p->z);
861                         if ((tmp[0] == 'A') || (tmp[0] == 'D')) {
862                                 send_cwcidspill(p);
863                         }
864                 } else {
865                         if (option_verbose > 2)
866                                 ast_verbose(VERBOSE_PREFIX_3 "CPE does not support Call Waiting Caller*ID.\n");
867                         restore_conference(p);
868                 }
869         } else
870                 restore_conference(p);
871         return 0;
872 }
873
874 static int zt_callwait(struct ast_channel *ast)
875 {
876         struct zt_pvt *p = ast->pvt->pvt;
877         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
878         if (p->cidspill) {
879                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
880                 free(p->cidspill);
881         }
882         p->cidspill = malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4);
883         if (p->cidspill) {
884                 save_conference(p);
885                 /* Silence */
886                 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
887                 if (!p->callwaitrings && p->callwaitingcallerid) {
888                         ast_gen_cas(p->cidspill, 1, 2400 + 680);
889                         p->callwaitcas = 1;
890                         p->cidlen = 2400 + 680 + READ_SIZE * 4;
891                 } else {
892                         ast_gen_cas(p->cidspill, 1, 2400);
893                         p->callwaitcas = 0;
894                         p->cidlen = 2400 + READ_SIZE * 4;
895                 }
896                 p->cidpos = 0;
897                 send_callerid(p);
898         } else {
899                 ast_log(LOG_WARNING, "Unable to create SAS/CAS spill\n");
900                 return -1;
901         }
902         return 0;
903 }
904
905 static int zt_call(struct ast_channel *ast, char *dest, int timeout)
906 {
907         struct zt_pvt *p = ast->pvt->pvt;
908         int x, res, index;
909         char *c, *n, *l;
910         char callerid[256];
911         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
912                 ast_log(LOG_WARNING, "zt_call called on %s, neither down nor reserved\n", ast->name);
913                 return -1;
914         }
915         p->dialednone = 0;
916         switch(p->sig) {
917         case SIG_FXOLS:
918         case SIG_FXOGS:
919         case SIG_FXOKS:
920                 if (p->owner == ast) {
921                         /* Normal ring, on hook */
922                         
923                         /* Don't send audio while on hook, until the call is answered */
924                         p->dialing = 1;
925                         if (p->use_callerid) {
926                                 /* Generate the Caller-ID spill if desired */
927                                 if (p->cidspill) {
928                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
929                                         free(p->cidspill);
930                                 }
931                                 p->cidspill = malloc(MAX_CALLERID_SIZE);
932                                 p->callwaitcas = 0;
933                                 if (p->cidspill) {
934                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->callerid);
935                                         p->cidpos = 0;
936                                         send_callerid(p);
937                                 } else
938                                         ast_log(LOG_WARNING, "Unable to generate CallerID spill\n");
939                         }
940                         /* Select proper cadence */
941                         if ((p->distinctivering > 0) && (p->distinctivering <= NUM_CADENCE)) {
942                                 if (ioctl(zap_fd(p->z), ZT_SETCADENCE, &cadences[p->distinctivering-1]))
943                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
944                                 p->cidrings = cidrings[p->distinctivering - 1];
945                         } else {
946                                 if (ioctl(zap_fd(p->z), ZT_SETCADENCE, NULL))
947                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
948                                 p->cidrings = 1;
949                         }
950                         x = ZT_RING;
951                         if (ioctl(zap_fd(p->z), ZT_HOOK, &x) && (errno != EINPROGRESS)) {
952                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
953                                 return -1;
954                         }
955                         p->dialing = 1;
956                 } else {
957                         /* Call waiting call */
958                         p->callwaitrings = 0;
959                         if (ast->callerid)
960                                 strncpy(p->callwaitcid, ast->callerid, sizeof(p->callwaitcid)-1);
961                         else
962                                 strcpy(p->callwaitcid, "");
963                         /* Call waiting tone instead */
964                         if (zt_callwait(ast))
965                                 return -1;
966                                 
967                 }
968                 ast_setstate(ast, AST_STATE_RINGING);
969                 index = zt_get_index(ast, p, 0);
970                 if (index > -1) {
971                         p->needringing[index] = 1;
972                 }
973                 break;
974         case SIG_FXSLS:
975         case SIG_FXSGS:
976         case SIG_FXSKS:
977         case SIG_EMWINK:
978         case SIG_EM:
979         case SIG_FEATD:
980         case SIG_FEATDMF:
981         case SIG_FEATB:
982                 c = strchr(dest, '/');
983                 if (c)
984                         c++;
985                 else
986                         c = dest;
987                 if (strlen(c) < p->stripmsd) {
988                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
989                         return -1;
990                 }
991                 x = ZT_START;
992                 /* Start the trunk */
993                 res = ioctl(zap_fd(p->z), ZT_HOOK, &x);
994                 if (res < 0) {
995                         if (errno != EINPROGRESS) {
996                                 ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
997                                 return -1;
998                         }
999                 }
1000                 ast_log(LOG_DEBUG, "Dialing '%s'\n", c);
1001                 p->dop.op = ZT_DIAL_OP_REPLACE;
1002                 if (p->sig == SIG_FEATD) {
1003                         if (ast->callerid) {
1004                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1005                                 ast_callerid_parse(callerid, &n, &l);
1006                                 if (l) {
1007                                         ast_shrink_phone_number(l);
1008                                         if (!ast_isphonenumber(l))
1009                                                 l = NULL;
1010                                 }
1011                         } else
1012                                 l = NULL;
1013                         if (l) 
1014                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c + p->stripmsd);
1015                         else
1016                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c + p->stripmsd);
1017                 } else 
1018                 if (p->sig == SIG_FEATDMF) {
1019                         if (ast->callerid) {
1020                                 strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1021                                 ast_callerid_parse(callerid, &n, &l);
1022                                 if (l) {
1023                                         ast_shrink_phone_number(l);
1024                                         if (!ast_isphonenumber(l))
1025                                                 l = NULL;
1026                                 }
1027                         } else
1028                                 l = NULL;
1029                         if (l) 
1030                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c + p->stripmsd);
1031                         else
1032                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c + p->stripmsd);
1033                 } else 
1034                 if (p->sig == SIG_FEATB) {
1035                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c + p->stripmsd);
1036                 } else 
1037                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", c + p->stripmsd);
1038                 if (!res) {
1039                         if (ioctl(zap_fd(p->z), ZT_DIAL, &p->dop)) {
1040                                 x = ZT_ONHOOK;
1041                                 ioctl(zap_fd(p->z), ZT_HOOK, &x);
1042                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
1043                                 return -1;
1044                         }
1045                 } else
1046                         ast_log(LOG_DEBUG, "Deferring dialing...\n");
1047                 p->dialing = 1;
1048                 if (strlen(c + p->stripmsd) < 1) p->dialednone = 1;
1049                 ast_setstate(ast, AST_STATE_DIALING);
1050                 break;
1051 #ifdef ZAPATA_PRI
1052         case SIG_PRI:
1053                 c = strchr(dest, '/');
1054                 if (c)
1055                         c++;
1056                 else
1057                         c = dest;
1058                 if (ast->callerid) {
1059                         strncpy(callerid, ast->callerid, sizeof(callerid)-1);
1060                         ast_callerid_parse(callerid, &n, &l);
1061                         if (l) {
1062                                 ast_shrink_phone_number(l);
1063                                 if (!ast_isphonenumber(l))
1064                                         l = NULL;
1065                         }
1066                 } else
1067                         l = NULL;
1068                 if (strlen(c) < p->stripmsd) {
1069                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
1070                         return -1;
1071                 }
1072                 if (pri_call(p->pri->pri, p->call, PRI_TRANS_CAP_SPEECH, 
1073                         ((p->channel - 1) % p->pri->channels) + 1, p->pri->nodetype == PRI_NETWORK ? 0 : 1, 1, l, PRI_NATIONAL_ISDN, 
1074                         l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE,
1075                         c + p->stripmsd, PRI_NATIONAL_ISDN, 
1076                         ((p->law == ZT_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW))) {
1077                         ast_log(LOG_WARNING, "Unable to setup call to %s\n", c + p->stripmsd);
1078                         return -1;
1079                 }
1080                 break;
1081 #endif          
1082         case 0:
1083                 /* Special pseudo -- automatically up*/
1084                 ast_setstate(ast, AST_STATE_UP);
1085                 break;          
1086         default:
1087                 ast_log(LOG_DEBUG, "not yet implemented\n");
1088                 return -1;
1089         }
1090         return 0;
1091 }
1092
1093 static int destroy_channel(struct zt_pvt *prev, struct zt_pvt *cur, int now)
1094 {
1095         int owned = 0;
1096         int i = 0;
1097         int res = 0;
1098
1099         if (!now) {
1100                 if (cur->owner) {
1101                         owned = 1;
1102                 }
1103
1104                 for (i = 0; i < 3; i++) {
1105                         if (cur->owners[i]) {
1106                                 owned = 1;
1107                         }
1108                 }
1109                 if (!owned) {
1110                         if (prev) {
1111                                 prev->next = cur->next;
1112                         } else {
1113                                 iflist = cur->next;
1114                         }
1115                         res = zap_close(cur->z);
1116                         if (res) {
1117                                 ast_log(LOG_ERROR, "Unable to close device on channel %d\n", cur->channel);
1118                                 free(cur);
1119                                 return -1;
1120                         }
1121                         free(cur);
1122                 }
1123         } else {
1124                 if (prev) {
1125                         prev->next = cur->next;
1126                 } else {
1127                         iflist = cur->next;
1128                 }
1129                 res = zap_close(cur->z);
1130                 if (res) {
1131                         ast_log(LOG_ERROR, "Unable to close device on channel %d\n", cur->channel);
1132                         free(cur);
1133                         return -1;
1134                 }
1135                 free(cur);
1136         }
1137         return 0;
1138 }
1139
1140
1141 static int zt_hangup(struct ast_channel *ast)
1142 {
1143         int res;
1144         int index,x, law;
1145         static int restore_gains(struct zt_pvt *p);
1146         struct zt_pvt *p = ast->pvt->pvt;
1147         struct zt_pvt *tmp = NULL;
1148         struct zt_pvt *prev = NULL;
1149         ZT_PARAMS par;
1150
1151         if (option_debug)
1152                 ast_log(LOG_DEBUG, "zt_hangup(%s)\n", ast->name);
1153         if (!ast->pvt->pvt) {
1154                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
1155                 return 0;
1156         }
1157         index = zt_get_index(ast, p, 1);
1158
1159         restore_gains(p);
1160         zap_digitmode(p->z,0);
1161
1162         ast_setstate(ast, AST_STATE_DOWN);
1163         ast_log(LOG_DEBUG, "Hangup: index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
1164                 index, p->normalindex, p->callwaitindex, p->thirdcallindex);
1165         p->ignoredtmf = 0;
1166         
1167         if (index > -1) {
1168                 /* Real channel, do some fixup */
1169                 p->owners[index] = NULL;
1170                 p->needanswer[index] = 0;
1171                 p->needringing[index] = 0;
1172                 if (index == p->normalindex) {
1173                         p->normalindex = -1;
1174                         if ((p->callwaitindex > -1) && (p->thirdcallindex > -1)) 
1175                                 ast_log(LOG_WARNING, "Normal call hung up with both three way call and a call waiting call in place?\n");
1176                         if (p->callwaitindex > -1) {
1177                                 /* If we hung up the normal call, make the call wait call
1178                                    be the normal call if there was one */
1179                                 p->normalindex = p->callwaitindex;
1180                                 p->callwaitindex = -1;
1181                         } else if (p->thirdcallindex > -1) {
1182                                 /* This was part of a three way call */
1183                                 p->normalindex = p->thirdcallindex;
1184                                 p->owners[p->normalindex]->fds[0] = zap_fd(p->z);
1185                                 p->owner = p->owners[p->normalindex];
1186                                 p->thirdcallindex = -1;
1187                                 unalloc_pseudo(p);
1188                         }
1189                 } else if (index == p->callwaitindex) {
1190                         /* If this was a call waiting call, mark the call wait
1191                            index as -1, so we know iavailable again */
1192                         p->callwaitindex = -1;
1193                 } else if (index == p->thirdcallindex) {
1194                         /* If this was part of a three way call index, let us make
1195                            another three way call */
1196                         p->thirdcallindex = -1;
1197                         unalloc_pseudo(p);
1198                 } else {
1199                         /* This wasn't any sort of call, but how are we an index? */
1200                         ast_log(LOG_WARNING, "Index found but not any type of call?\n");
1201                 }
1202         }
1203
1204
1205         if (!p->owners[0] && !p->owners[1] && !p->owners[2]) {
1206                 p->owner = NULL;
1207                 p->ringt = 0;
1208                 p->distinctivering = 0;
1209                 p->confirmanswer = 0;
1210                 p->cidrings = 1;
1211                 law = ZT_LAW_DEFAULT;
1212                 res = ioctl(zap_fd(p->z), ZT_SETLAW, &law);
1213                 p->reallinear = 0;
1214                 zap_setlinear(p->z, 0);
1215                 if (res < 0) 
1216                         ast_log(LOG_WARNING, "Unable to set law on channel %d to default\n", p->channel);
1217                 /* Perform low level hangup if no owner left */
1218 #ifdef ZAPATA_PRI
1219                 if (p->sig == SIG_PRI) {
1220                         if (p->call) {
1221                                 if (!pri_grab(p->pri)) {
1222                                         res = pri_disconnect(p->pri->pri, p->call, PRI_CAUSE_NORMAL_CLEARING);
1223                                         p->call = NULL;
1224                                         if (res < 0) 
1225                                                 ast_log(LOG_WARNING, "pri_disconnect failed\n");
1226                                         pri_rel(p->pri);                        
1227                                 } else {
1228                                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1229                                         res = -1;
1230                                 }
1231                         } else
1232                                 res = 0;
1233
1234                 } else 
1235 #endif
1236                 if (p->sig)
1237                         res = zt_set_hook(zap_fd(p->z), ZT_ONHOOK);
1238                 if (res < 0) {
1239                         ast_log(LOG_WARNING, "Unable to hangup line %s\n", ast->name);
1240                         return -1;
1241                 }
1242                 switch(p->sig) {
1243                 case SIG_FXOGS:
1244                 case SIG_FXOLS:
1245                 case SIG_FXOKS:
1246                         res = ioctl(zap_fd(p->z), ZT_GET_PARAMS, &par);
1247                         if (!res) {
1248 #if 0
1249                                 ast_log(LOG_DEBUG, "Hanging up channel %d, offhook = %d\n", p->channel, par.rxisoffhook);
1250 #endif
1251                                 /* If they're off hook, try playing congestion */
1252                                 if (par.rxisoffhook)
1253                                         tone_zone_play_tone(zap_fd(p->z), ZT_TONE_CONGESTION);
1254                                 else
1255                                         tone_zone_play_tone(zap_fd(p->z), -1);
1256                         }
1257                         break;
1258                 default:
1259                         tone_zone_play_tone(zap_fd(p->z), -1);
1260                 }
1261                 if (index > -1) {
1262                         p->needringing[index] = 0;
1263                         p->needanswer[index] = 0;
1264                 }
1265                 if (p->cidspill)
1266                         free(p->cidspill);
1267                 if (p->sig)
1268                         zt_disable_ec(p);
1269                 x = 0;
1270                 ast_channel_setoption(ast,AST_OPTION_TONE_VERIFY,&x,sizeof(char),0);
1271                 ast_channel_setoption(ast,AST_OPTION_TDD,&x,sizeof(char),0);
1272                 p->didtdd = 0;
1273                 p->cidspill = NULL;
1274                 p->callwaitcas = 0;
1275                 p->callwaiting = p->permcallwaiting;
1276                 p->hidecallerid = p->permhidecallerid;
1277                 p->dialing = 0;
1278                 conf_clear(p);
1279                 unalloc_pseudo(p);
1280                 restart_monitor();
1281         }
1282
1283
1284         p->callwaitingrepeat = 0;
1285         ast->pvt->pvt = NULL;
1286         ast_setstate(ast, AST_STATE_DOWN);
1287         ast_pthread_mutex_lock(&usecnt_lock);
1288         usecnt--;
1289         if (usecnt < 0) 
1290                 ast_log(LOG_WARNING, "Usecnt < 0???\n");
1291         ast_pthread_mutex_unlock(&usecnt_lock);
1292         ast_update_use_count();
1293         if (option_verbose > 2) 
1294                 ast_verbose( VERBOSE_PREFIX_3 "Hungup '%s'\n", ast->name);
1295
1296         ast_pthread_mutex_lock(&iflock);
1297         tmp = iflist;
1298         prev = NULL;
1299         if (p->destroy) {
1300                 while (tmp) {
1301                         if (tmp == p) {
1302                                 destroy_channel(prev, tmp, 0);
1303                                 break;
1304                         } else {
1305                                 prev = tmp;
1306                                 tmp = tmp->next;
1307                         }
1308                 }
1309         }
1310         ast_pthread_mutex_unlock(&iflock);
1311         return 0;
1312 }
1313
1314 static int zt_answer(struct ast_channel *ast)
1315 {
1316         struct zt_pvt *p = ast->pvt->pvt;
1317         int res=0;
1318         ast_setstate(ast, AST_STATE_UP);
1319         switch(p->sig) {
1320         case SIG_FXSLS:
1321         case SIG_FXSGS:
1322         case SIG_FXSKS:
1323                 p->ringt = 0;
1324                 /* Fall through */
1325         case SIG_EM:
1326         case SIG_EMWINK:
1327         case SIG_FEATD:
1328         case SIG_FEATDMF:
1329         case SIG_FEATB:
1330         case SIG_FXOLS:
1331         case SIG_FXOGS:
1332         case SIG_FXOKS:
1333                 /* Pick up the line */
1334                 ast_log(LOG_DEBUG, "Took %s off hook\n", ast->name);
1335                 res =  zt_set_hook(zap_fd(p->z), ZT_OFFHOOK);
1336                 tone_zone_play_tone(zap_fd(p->z), -1);
1337                 if (INTHREEWAY(p))
1338                         tone_zone_play_tone(zap_fd(p->pseudo), -1);
1339                 p->dialing = 0;
1340                 break;
1341 #ifdef ZAPATA_PRI
1342         case SIG_PRI:
1343                 /* Send a pri acknowledge */
1344                 if (!pri_grab(p->pri)) {
1345                         res = pri_answer(p->pri->pri, p->call, 0, 1);
1346                         pri_rel(p->pri);
1347                 } else {
1348                         ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", p->span);
1349                         res= -1;
1350                 }
1351                 break;
1352 #endif          
1353         default:
1354                 ast_log(LOG_WARNING, "Don't know how to answer signalling %d (channel %d)\n", p->sig, p->channel);
1355                 return -1;
1356         }
1357         return res;
1358 }
1359
1360 static inline int bridge_cleanup(struct zt_pvt *p0, struct zt_pvt *p1)
1361 {
1362         int res = 0;
1363         if (p0) {
1364                 res = conf_clear(p0);
1365                 if (!p0->echocanbridged)
1366                         zt_enable_ec(p0);
1367         }
1368         if (p1) {
1369                 res |= conf_clear(p1);
1370                 if (!p1->echocanbridged)
1371                         zt_enable_ec(p1);
1372         }       
1373         return res;
1374 }
1375
1376 static int zt_setoption(struct ast_channel *chan, int option, void *data, int datalen)
1377 {
1378 char    *cp;
1379
1380         struct zt_pvt *p = chan->pvt->pvt;
1381
1382         
1383         if ((option != AST_OPTION_TONE_VERIFY) &&
1384                 (option != AST_OPTION_TDD))
1385            {
1386                 errno = ENOSYS;
1387                 return -1;
1388            }
1389         cp = (char *)data;
1390         if ((!cp) || (datalen < 1))
1391            {
1392                 errno = EINVAL;
1393                 return -1;
1394            }
1395         switch(option) {
1396             case AST_OPTION_TONE_VERIFY:
1397                 switch(*cp) {
1398                     case 1:
1399                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF(1) on %s\n",chan->name);
1400                         zap_digitmode(p->z,ZAP_MUTECONF);  /* set mute mode if desired */
1401                         break;
1402                     case 2:
1403                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: MUTECONF/MAX(2) on %s\n",chan->name);
1404                         zap_digitmode(p->z,ZAP_MUTECONF | ZAP_MUTEMAX);  /* set mute mode if desired */
1405                         break;
1406                     default:
1407                         ast_log(LOG_DEBUG, "Set option TONE VERIFY, mode: OFF(0) on %s\n",chan->name);
1408                         zap_digitmode(p->z,0);  /* set mute mode if desired */
1409                         break;
1410                 }
1411                 break;
1412             case AST_OPTION_TDD:  /* turn on or off TDD */
1413                 if (!*cp) { /* turn it off */
1414                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: OFF(0) on %s\n",chan->name);
1415                         if (p->tdd) tdd_free(p->tdd);
1416                         p->tdd = 0;
1417                         p->mate = 0;
1418                         break;
1419                 }
1420                 if (*cp == 2)
1421                         ast_log(LOG_DEBUG, "Set option TDD MODE, value: MATE(2) on %s\n",chan->name);
1422                 else ast_log(LOG_DEBUG, "Set option TDD MODE, value: ON(1) on %s\n",chan->name);
1423                 p->mate = 0;
1424                 zt_disable_ec(p);
1425                 /* otherwise, turn it on */
1426                 if (!p->didtdd) { /* if havent done it yet */
1427                         unsigned char mybuf[41000],*buf;
1428                         int size,res,fd,len;
1429                         fd_set wfds,efds;
1430                         buf = mybuf;
1431                         memset(buf,0x7f,sizeof(mybuf)); /* set to silence */
1432                         ast_tdd_gen_ecdisa(buf + 16000,16000);  /* put in tone */
1433                         len = 40000;
1434                         if (chan != p->owner)   /* if in three-way */
1435                                 fd = zap_fd(p->pseudo);
1436                         else
1437                                 fd = zap_fd(p->z);
1438                         while(len) {
1439                                 if (ast_check_hangup(chan)) return -1;
1440                                 size = len;
1441                                 if (size > READ_SIZE)
1442                                         size = READ_SIZE;
1443                                 FD_ZERO(&wfds);
1444                                 FD_ZERO(&efds);
1445                                 FD_SET(fd,&wfds);
1446                                 FD_SET(fd,&efds);                       
1447                                 res = select(fd + 1,NULL,&wfds,&efds,NULL);
1448                                 if (!res) {
1449                                         ast_log(LOG_DEBUG, "select (for write) ret. 0 on channel %d\n", p->channel);
1450                                         continue;
1451                                 }
1452                                   /* if got exception */
1453                                 if (FD_ISSET(fd,&efds)) return -1;
1454                                 if (!FD_ISSET(fd,&wfds)) {
1455                                         ast_log(LOG_DEBUG, "write fd not ready on channel %d\n", p->channel);
1456                                         continue;
1457                                 }
1458                                 res = write(fd, buf, size);
1459                                 if (res != size) {
1460                                         if (res == -1) return -1;
1461                                         ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
1462                                         break;
1463                                 }
1464                                 len -= size;
1465                                 buf += size;
1466                         }
1467                         p->didtdd = 1; /* set to have done it now */            
1468                 }
1469                 if (*cp == 2) { /* Mate mode */
1470                         if (p->tdd) tdd_free(p->tdd);
1471                         p->tdd = 0;
1472                         p->mate = 1;
1473                         break;
1474                         }               
1475                 if (!p->tdd) { /* if we dont have one yet */
1476                         p->tdd = tdd_new(); /* allocate one */
1477                 }               
1478                 break;
1479         }
1480         errno = 0;
1481         return 0;
1482 }
1483
1484 static int zt_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc)
1485 {
1486         /* Do a quickie conference between the two channels and wait for something to happen */
1487         struct zt_pvt *p0 = c0->pvt->pvt;
1488         struct zt_pvt *p1 = c1->pvt->pvt;
1489         struct ast_channel *who = NULL, *cs[3];
1490         struct ast_frame *f;
1491         int to = -1;
1492         int firstpass = 1;
1493         
1494         int confno = -1;
1495         
1496           /* if need DTMF, cant native bridge */
1497         if (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))
1498                 return -2;
1499           /* if cant run clear DTMF, cant native bridge */
1500         ast_pthread_mutex_lock(&c0->lock);
1501         ast_pthread_mutex_lock(&c1->lock);
1502         if (!CLEARDTMF(c0) || !CLEARDTMF(c1)) {
1503                 pthread_mutex_unlock(&c1->lock);
1504                 pthread_mutex_unlock(&c0->lock);
1505                 return -3;
1506         }
1507         p0 = c0->pvt->pvt;
1508         p1 = c1->pvt->pvt;
1509         if (c0->type == type)
1510                 /* Stop any playing tones */
1511                 tone_zone_play_tone(zap_fd(p0->z),      -1);
1512         if (c1->type == type)
1513                 tone_zone_play_tone(zap_fd(p1->z),      -1);
1514         pthread_mutex_unlock(&c1->lock);
1515         pthread_mutex_unlock(&c0->lock);
1516
1517         cs[0] = c0;
1518         cs[1] = c1;
1519         for (;;) {
1520                 ast_pthread_mutex_lock(&c0->lock);
1521                 ast_pthread_mutex_lock(&c1->lock);
1522                 p0 = c0->pvt->pvt;
1523                 p1 = c1->pvt->pvt;
1524
1525                 /* Stop if we're a zombie or need a soft hangup */
1526                 if (c0->zombie || ast_check_hangup(c0) || c1->zombie || ast_check_hangup(c1)) {
1527                         *fo = NULL;
1528                         if (who) *rc = who;
1529                         bridge_cleanup(p0, p1);
1530                         pthread_mutex_unlock(&c0->lock);
1531                         pthread_mutex_unlock(&c1->lock);
1532                         return 0;
1533                 }
1534                 if (!p0 || !p1 || (c0->type != type) || (c1->type != type)) {
1535                         if (!firstpass) {
1536                                 if ((c0->type == type) && !p0->echocanbridged)
1537                                         zt_enable_ec(p0);
1538                                 if ((c1->type == type) && !p1->echocanbridged)
1539                                         zt_enable_ec(p1);
1540                         }
1541                         pthread_mutex_unlock(&c0->lock);
1542                         pthread_mutex_unlock(&c1->lock);
1543                         return -2;
1544                 }
1545
1546                 if (firstpass) {
1547                         /* Only do this once, turning off echo cancellation if this is a native bridge
1548                            with bridged echo cancellation turned off */
1549                         if (!p0->echocanbridged)
1550                                 zt_disable_ec(p0);
1551                         if (!p1->echocanbridged)
1552                                 zt_disable_ec(p1);
1553                         firstpass = 0;
1554                 }
1555                 if (INTHREEWAY(p0) && (c0 == p0->owners[p0->thirdcallindex]))
1556                         tone_zone_play_tone(zap_fd(p0->pseudo), -1);
1557                 if (INTHREEWAY(p1) && (c1 == p1->owners[p1->thirdcallindex]))
1558                         tone_zone_play_tone(zap_fd(p1->pseudo), -1);
1559                 if (INTHREEWAY(p0) && (INTHREEWAY(p1))) {
1560                         ast_log(LOG_WARNING, "Too weird, can't bridge multiple three way calls\n");
1561                         if (!p0->echocanbridged)
1562                                 zt_enable_ec(p0);
1563                         if (!p1->echocanbridged)
1564                                 zt_enable_ec(p1);
1565                         pthread_mutex_unlock(&c0->lock);
1566                         pthread_mutex_unlock(&c1->lock);
1567                         return -1;
1568                 }
1569                 if ((p0->owner == c0) && (p1->owner == c1)) {
1570                         /* Okay, this call should actually be connected */
1571                         if ((p0->confno > -1) && (p1->confno > -1) && (p0->confno != p1->confno)) {
1572                                 /* We have a conflict here.  Try to resolve it. */
1573                                 if ((INTHREEWAY(p0) && (c0 == p0->owners[p0->normalindex]))) {
1574                                         ast_log(LOG_DEBUG, "Channel %s is in a three way call with us, moving to our conference %d\n",
1575                                                 c1->name, p0->confno);
1576                                         conf_set(p1, p0->confno, 1);
1577                                 } else if (INTHREEWAY(p1) && (c1 == p1->owners[p1->normalindex])) {
1578                                                 ast_log(LOG_DEBUG, "Channel %s is in a three way call with us, moving to our conference %d\n",
1579                                                         c0->name, p1->confno);
1580                                                 conf_set(p0, p1->confno, 1);
1581                                 } else {
1582                                         ast_log(LOG_WARNING, "Can't bridge since %s is on conf %d and %s is on conf %d\n",
1583                                                 c0->name, p0->confno, c1->name, p1->confno);
1584                                         if (!p0->echocanbridged)
1585                                                 zt_enable_ec(p0);
1586                                         if (!p1->echocanbridged)
1587                                                 zt_enable_ec(p1);
1588                                         pthread_mutex_unlock(&c0->lock);
1589                                         pthread_mutex_unlock(&c1->lock);
1590                                         return -1;
1591                                 }
1592                         }
1593                         if (p0->confno > -1)
1594                                 confno = p0->confno;
1595                         else
1596                                 confno = p1->confno;
1597                         if (confno < 0) {
1598                                 conf_set(p0, -1, 0);
1599                                 confno = p0->confno;
1600                                 ast_log(LOG_DEBUG, "Creating new conference %d for %s\n", confno, c0->name);
1601                         }
1602                         if (p0->confno != confno) {
1603                                 ast_log(LOG_DEBUG, "Placing %s in conference %d\n", c0->name, confno);
1604                                 conf_set(p0, confno, 0);
1605                         }
1606                         if (p1->confno != confno) {
1607                                 ast_log(LOG_DEBUG, "Placing %s in conference %d\n", c1->name, confno);
1608                                 conf_set(p1, confno, 0);
1609                         }
1610                 } else if (INTHREEWAY(p0) && (c0 == p0->owners[p0->thirdcallindex])) {
1611                         /* p0 is in a three way call and we're the third leg.  Join their
1612                            conference, already in progress if there is one */
1613                         if ((p0->confno > -1) && (p1->confno != p0->confno)) {
1614                                 confno = p0->confno;
1615                                 ast_log(LOG_DEBUG, "Placing %s in conference %d\n", c1->name, confno);
1616                                 conf_set(p1, confno, 0);
1617                         }
1618                 } else if (INTHREEWAY(p1) && (c1 == p1->owners[p1->thirdcallindex])) {
1619                         /* p0 is in a three way call and we're the third leg.  Join their
1620                            conference, already in progress if there is one */
1621                         if ((p1->confno > -1) && (p1->confno != p0->confno)) {
1622                                 confno = p0->confno;
1623                                 ast_log(LOG_DEBUG, "Placing %s in conference %d\n", c0->name, confno);
1624                                 conf_set(p0, confno, 0);
1625                         }
1626                 }
1627                 pthread_mutex_unlock(&c0->lock);
1628                 pthread_mutex_unlock(&c1->lock);
1629                 
1630                 who = ast_waitfor_n(cs, 2, &to);
1631                 if (!who) {
1632                         ast_log(LOG_WARNING, "Nobody there??\n");
1633                         continue;
1634                 }
1635                   /* if gone out of CLEAR DTMF mode */
1636                 if (!CLEARDTMF(c0) || !CLEARDTMF(c1)) {
1637                         *fo = NULL;
1638                         *rc = who;
1639                         bridge_cleanup(p0, p1);
1640                         return -3;
1641                 }
1642                 if (who == c0)
1643                         p0->ignoredtmf = 1;
1644                 else
1645                         p1->ignoredtmf = 1;
1646                 f = ast_read(who);
1647                 if (who == c0)
1648                         p0->ignoredtmf = 0;
1649                 else
1650                         p1->ignoredtmf = 0;
1651                 if (!f) {
1652                         *fo = NULL;
1653                         *rc = who;
1654                         bridge_cleanup(p0, p1);
1655                         return 0;
1656                 }
1657                 if ((f->frametype == AST_FRAME_CONTROL) && !(flags & AST_BRIDGE_IGNORE_SIGS)) {
1658                         *fo = f;
1659                         *rc = who;
1660                         bridge_cleanup(p0, p1);
1661                         return 0;
1662                 }
1663                 if ((f->frametype == AST_FRAME_VOICE) ||
1664                         (f->frametype == AST_FRAME_TEXT) ||
1665                         (f->frametype == AST_FRAME_VIDEO) || 
1666                         (f->frametype == AST_FRAME_IMAGE) ||
1667                         (f->frametype == AST_FRAME_DTMF)) {
1668                         if ((f->frametype == AST_FRAME_DTMF) && (flags & (AST_BRIDGE_DTMF_CHANNEL_0 | AST_BRIDGE_DTMF_CHANNEL_1))) {
1669                                 if ((who == c0) && (flags & AST_BRIDGE_DTMF_CHANNEL_0)) {
1670                                         *rc = c0;
1671                                         *fo = f;
1672                                         bridge_cleanup(p0, p1);
1673                                         return 0;
1674                                 } else
1675                                 if ((who == c1) && (flags & AST_BRIDGE_DTMF_CHANNEL_1)) {
1676                                         *rc = c1;
1677                                         *fo = f;
1678                                         bridge_cleanup(p0, p1);
1679                                         return 0;
1680                                 }
1681                         }
1682                         ast_frfree(f);
1683                 } else
1684                         ast_frfree(f);
1685                 /* Swap who gets priority */
1686                 cs[2] = cs[0];
1687                 cs[0] = cs[1];
1688                 cs[1] = cs[2];
1689         }
1690         return 0;
1691 }
1692
1693 static int zt_indicate(struct ast_channel *chan, int condition);
1694
1695 static int zt_fixup(struct ast_channel *oldchan, struct ast_channel *newchan)
1696 {
1697         struct zt_pvt *p = newchan->pvt->pvt;
1698         int x;
1699         ast_log(LOG_DEBUG, "New owner for channel %d is %s\n", p->channel, newchan->name);
1700         p->owner = newchan;
1701         for (x=0;x<3;x++)
1702                 if (p->owners[x] == oldchan)
1703                         p->owners[x] = newchan;
1704         if (newchan->_state == AST_STATE_RINGING) 
1705                 zt_indicate(newchan, AST_CONTROL_RINGING);
1706         return 0;
1707 }
1708
1709 static int zt_ring_phone(struct zt_pvt *p)
1710 {
1711         int x;
1712         int res;
1713         /* Make sure our transmit state is on hook */
1714         x = 0;
1715         x = ZT_ONHOOK;
1716         res = ioctl(zap_fd(p->z), ZT_HOOK, &x);
1717         do {
1718                 x = ZT_RING;
1719                 res = ioctl(zap_fd(p->z), ZT_HOOK, &x);
1720 #if 0
1721                 printf("Res: %d, error: %s\n", res, strerror(errno));
1722 #endif                                          
1723                 if (res) {
1724                         switch(errno) {
1725                         case EBUSY:
1726                         case EINTR:
1727                                 /* Wait just in case */
1728                                 usleep(10000);
1729                                 continue;
1730                         case EINPROGRESS:
1731                                 res = 0;
1732                                 break;
1733                         default:
1734                                 ast_log(LOG_WARNING, "Couldn't ring the phone: %s\n", strerror(errno));
1735                                 res = 0;
1736                         }
1737                 }
1738         } while (res);
1739         return res;
1740 }
1741
1742 static void *ss_thread(void *data);
1743
1744 static struct ast_channel *zt_new(struct zt_pvt *, int, int, int, int);
1745
1746 static int attempt_transfer(struct zt_pvt *p)
1747 {
1748         /* In order to transfer, we need at least one of the channels to
1749            actually be in a call bridge.  We can't conference two applications
1750            together (but then, why would we want to?) */
1751         if (p->owners[p->normalindex]->bridge) {
1752                 if (ast_channel_masquerade(p->owners[p->thirdcallindex], p->owners[p->normalindex]->bridge)) {
1753                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
1754                                         p->owners[p->normalindex]->bridge->name, p->owners[p->thirdcallindex]->name);
1755                         return -1;
1756                 }
1757                 /* Orphan the channel */
1758                 p->owners[p->thirdcallindex] = NULL;
1759                 p->thirdcallindex = -1;
1760         } else if (p->owners[p->thirdcallindex]->bridge) {
1761                 if (ast_channel_masquerade(p->owners[p->normalindex], p->owners[p->thirdcallindex]->bridge)) {
1762                         ast_log(LOG_WARNING, "Unable to masquerade %s as %s\n",
1763                                 p->owners[p->thirdcallindex]->bridge->name, p->owners[p->normalindex]->name);
1764                         return -1;
1765                 }
1766                 /* Orphan the normal channel */
1767                 p->owners[p->normalindex] = NULL;
1768                 p->normalindex = p->thirdcallindex;
1769                 p->thirdcallindex = -1;
1770         } else {
1771                 ast_log(LOG_DEBUG, "Neither %s nor %s are in a bridge, nothing to transfer\n",
1772                                         p->owners[p->normalindex]->name, p->owners[p->thirdcallindex]->name);
1773                 p->owners[p->thirdcallindex]->_softhangup |= AST_SOFTHANGUP_DEV;
1774         }
1775         return 0;
1776 }
1777
1778 struct ast_frame *zt_handle_event(struct ast_channel *ast)
1779 {
1780         int res,x;
1781         int index;
1782         struct zt_pvt *p = ast->pvt->pvt;
1783         pthread_t threadid;
1784         pthread_attr_t attr;
1785         struct ast_channel *chan;
1786         pthread_attr_init(&attr);
1787         pthread_attr_setdetachstate(&attr, PTHREAD_CREATE_DETACHED);
1788         index = zt_get_index(ast, p, 0);
1789         p->f[index].frametype = AST_FRAME_NULL;
1790         p->f[index].datalen = 0;
1791         p->f[index].timelen = 0;
1792         p->f[index].mallocd = 0;
1793         p->f[index].offset = 0;
1794         p->f[index].src = "zt_handle_event";
1795         p->f[index].data = NULL;
1796         if (index < 0)
1797                 return &p->f[index];
1798         res = zt_get_event(zap_fd(p->z));
1799         ast_log(LOG_DEBUG, "Got event %s(%d) on channel %d (index %d)\n", event2str(res), res, p->channel, index);
1800         switch(res) {
1801                 case ZT_EVENT_DIALCOMPLETE:
1802                         if (p->inalarm) break;
1803                         if (ioctl(zap_fd(p->z),ZT_DIALING,&x) == -1) {
1804                                 ast_log(LOG_DEBUG, "ZT_DIALING ioctl failed on %s\n",ast->name);
1805                                 return NULL;
1806                         }
1807                         if (!x) { /* if not still dialing in driver */
1808                                 zt_enable_ec(p);
1809                                 p->dialing = 0;
1810                                 if (ast->_state == AST_STATE_DIALING) {
1811                                         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)))) {
1812                                                 ast_setstate(ast, AST_STATE_RINGING);
1813                                         } else {
1814                                                 ast_setstate(ast, AST_STATE_UP);
1815                                                 p->f[index].frametype = AST_FRAME_CONTROL;
1816                                                 p->f[index].subclass = AST_CONTROL_ANSWER;
1817                                         }
1818                                 }
1819                         }
1820                         break;
1821                 case ZT_EVENT_ALARM:
1822                         p->inalarm = 1;
1823                         /* fall through intentionally */
1824                 case ZT_EVENT_ONHOOK:
1825                         switch(p->sig) {
1826                         case SIG_FXOLS:
1827                         case SIG_FXOGS:
1828                         case SIG_FXOKS:
1829                                 /* Check for some special conditions regarding call waiting */
1830                                 if (index == p->normalindex) {
1831                                         /* The normal line was hung up */
1832                                         if (p->callwaitindex > -1) {
1833                                                 bridge_cleanup(p->owners[p->normalindex]->pvt->pvt,
1834                                                     p->owners[p->callwaitindex]->pvt->pvt);
1835                                                 /* There's a call waiting call, so ring the phone */
1836                                                 p->owner = p->owners[p->callwaitindex];
1837                                                 if (option_verbose > 2) 
1838                                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %s still has (callwait) call, ringing phone\n", p->owner->name);
1839                                                 p->needanswer[index] = 0;
1840                                                 p->needringing[index] = 0;
1841                                                 p->callwaitingrepeat = 0;
1842                                                 zt_ring_phone(p);
1843                                         } else if (p->thirdcallindex > -1) {
1844                                                 if (p->transfer) {
1845                                                         if (attempt_transfer(p))
1846                                                                 p->owners[p->thirdcallindex]->_softhangup |= AST_SOFTHANGUP_DEV;
1847                                                 } else
1848                                                         p->owners[p->thirdcallindex]->_softhangup |= AST_SOFTHANGUP_DEV;
1849                                         }
1850                                 } else if (index == p->callwaitindex) {
1851                                         /* Check to see if there is a normal call */
1852                                         if (p->normalindex > -1) {
1853                                                 bridge_cleanup(p->owners[p->normalindex]->pvt->pvt,
1854                                                     p->owners[p->callwaitindex]->pvt->pvt);
1855                                                 /* There's a call waiting call, so ring the phone */
1856                                                 p->owner = p->owners[p->normalindex];
1857                                                 if (option_verbose > 2)
1858                                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %s still has (normal) call, ringing phone\n", p->owner->name);
1859                                                 p->needanswer[index] = 0;
1860                                                 p->needringing[index] = 0;
1861                                                 p->callwaitingrepeat = 0;
1862                                                 zt_ring_phone(p);
1863                                         }
1864                                 } else if (index == p->thirdcallindex) {
1865                                         if ((ast->_state != AST_STATE_UP) && (ast->_state != AST_STATE_RINGING) &&
1866                                                         (ast->_state != AST_STATE_RING)) {
1867                                                 /* According to the LSSGR, we should kill everything now, and we 
1868                                                    do, instead of ringing the phone */
1869                                                 if (p->normalindex > -1) 
1870                                                         p->owners[p->normalindex]->_softhangup |= AST_SOFTHANGUP_DEV;
1871                                                 if (p->callwaitindex > -1) {
1872                                                         ast_log(LOG_WARNING, "Somehow there was a call wait\n");
1873                                                         p->owners[p->callwaitindex]->_softhangup |= AST_SOFTHANGUP_DEV;
1874                                                 }
1875                                                 
1876                                         } else {
1877                                                 if (p->transfer) {
1878                                                         if (attempt_transfer(p))
1879                                                                 p->owners[p->normalindex]->_softhangup |= AST_SOFTHANGUP_DEV;
1880                                                         else {
1881                                                                 /* Don't actually hangup.  We're going to get transferred */
1882                                                                 zt_disable_ec(p);
1883                                                                 break;
1884                                                         }
1885                                                 } else 
1886                                                         p->owners[p->normalindex]->_softhangup |= AST_SOFTHANGUP_DEV;
1887                                         }
1888                                 }
1889                                 /* Fall through */
1890                         default:
1891                                 zt_disable_ec(p);
1892                                 return NULL;
1893                         }
1894                         break;
1895                 case ZT_EVENT_RINGOFFHOOK:
1896                         if (p->inalarm) break;
1897                         switch(p->sig) {
1898                         case SIG_FXOLS:
1899                         case SIG_FXOGS:
1900                         case SIG_FXOKS:
1901                                 switch(ast->_state) {
1902                                 case AST_STATE_RINGING:
1903                                         zt_enable_ec(p);
1904                                         p->f[index].frametype = AST_FRAME_CONTROL;
1905                                         p->f[index].subclass = AST_CONTROL_ANSWER;
1906                                         /* Make sure it stops ringing */
1907                                         zt_set_hook(zap_fd(p->z), ZT_OFFHOOK);
1908                                         ast_log(LOG_DEBUG, "channel %d answered\n", p->channel);
1909                                         if (p->cidspill) {
1910                                                 /* Cancel any running CallerID spill */
1911                                                 free(p->cidspill);
1912                                                 p->cidspill = NULL;
1913                                         }
1914                                         p->dialing = 0;
1915                                         if (p->confirmanswer) {
1916                                                 /* Ignore answer if "confirm answer" is selected */
1917                                                 p->f[index].frametype = AST_FRAME_NULL;
1918                                                 p->f[index].subclass = 0;
1919                                         } else 
1920                                                 ast_setstate(ast, AST_STATE_UP);
1921                                         return &p->f[index];
1922                                 case AST_STATE_DOWN:
1923                                         ast_setstate(ast, AST_STATE_RING);
1924                                         ast->rings = 1;
1925                                         p->f[index].frametype = AST_FRAME_CONTROL;
1926                                         p->f[index].subclass = AST_CONTROL_OFFHOOK;
1927                                         ast_log(LOG_DEBUG, "channel %d picked up\n", p->channel);
1928                                         return &p->f[index];
1929                                 case AST_STATE_UP:
1930                                         /* Make sure it stops ringing */
1931                                         zt_set_hook(zap_fd(p->z), ZT_OFFHOOK);
1932                                         /* Okay -- probably call waiting*/
1933                                         if (p->owner->bridge)
1934                                                         ast_moh_stop(p->owner->bridge);
1935                                         break;
1936                                 default:
1937                                         ast_log(LOG_WARNING, "FXO phone off hook in weird state %d??\n", ast->_state);
1938                                 }
1939                                 break;
1940                         case SIG_FXSLS:
1941                         case SIG_FXSGS:
1942                         case SIG_FXSKS:
1943                                 if (ast->_state == AST_STATE_RING) {
1944                                         p->ringt = RINGT;
1945                                 }
1946                                 /* Fall through */
1947                         case SIG_EM:
1948                         case SIG_EMWINK:
1949                         case SIG_FEATD:
1950                         case SIG_FEATDMF:
1951                         case SIG_FEATB:
1952                                 if (ast->_state == AST_STATE_DOWN) {
1953                                         if (option_debug)
1954                                                 ast_log(LOG_DEBUG, "Ring detected\n");
1955                                         p->f[index].frametype = AST_FRAME_CONTROL;
1956                                         p->f[index].subclass = AST_CONTROL_RING;
1957                                 } else if (ast->_state == AST_STATE_RINGING) {
1958                                         if (option_debug)
1959                                                 ast_log(LOG_DEBUG, "Line answered\n");
1960                                         if (p->confirmanswer) {
1961                                                 p->f[index].frametype = AST_FRAME_NULL;
1962                                                 p->f[index].subclass = 0;
1963                                         } else {
1964                                                 p->f[index].frametype = AST_FRAME_CONTROL;
1965                                                 p->f[index].subclass = AST_CONTROL_ANSWER;
1966                                                 ast_setstate(ast, AST_STATE_UP);
1967                                         }
1968                                 } else if (ast->_state != AST_STATE_RING)
1969                                         ast_log(LOG_WARNING, "Ring/Off-hook in strange state %d on channel %d\n", ast->_state, p->channel);
1970                                 break;
1971                         default:
1972                                 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
1973                         }
1974                         break;
1975                 case ZT_EVENT_RINGEROFF:
1976                         if (p->inalarm) break;
1977                         ast->rings++;
1978                         if ((ast->rings > p->cidrings) && (p->cidspill)) {
1979                                 ast_log(LOG_WARNING, "Didn't finish Caller-ID spill.  Cancelling.\n");
1980                                 free(p->cidspill);
1981                                 p->cidspill = NULL;
1982                                 p->callwaitcas = 0;
1983                         }
1984                         p->f[index].frametype = AST_FRAME_CONTROL;
1985                         p->f[index].subclass = AST_CONTROL_RINGING;
1986                         break;
1987                 case ZT_EVENT_RINGERON:
1988                         break;
1989                 case ZT_EVENT_NOALARM:
1990                         p->inalarm = 0;
1991                         break;
1992                 case ZT_EVENT_WINKFLASH:
1993                         if (p->inalarm) break;
1994                         switch(p->sig) {
1995                         case SIG_FXOLS:
1996                         case SIG_FXOGS:
1997                         case SIG_FXOKS:
1998                                 ast_log(LOG_DEBUG, "Winkflash, index: %d, normal: %d, callwait: %d, thirdcall: %d\n",
1999                                         index, p->normalindex, p->callwaitindex, p->thirdcallindex);
2000                                 if (index == p->normalindex) {
2001                                         if (p->callwaitindex > -1) {
2002                                                 tone_zone_play_tone(zap_fd(p->z), -1);
2003                                                 p->owner = p->owners[p->callwaitindex];
2004                                                 if (p->owner->_state == AST_STATE_RINGING) {
2005                                                         ast_setstate(p->owner, AST_STATE_UP);
2006                                                         p->needanswer[p->callwaitindex] = 1;
2007                                                 }
2008                                                 p->callwaitingrepeat = 0;
2009                                                 conf_clear(p);
2010                                                 /* Start music on hold if appropriate */
2011                                                 if (p->owners[p->normalindex]->bridge)
2012                                                                 ast_moh_start(p->owners[p->normalindex]->bridge, NULL);
2013                                                 if (p->owners[p->callwaitindex]->bridge)
2014                                                                 ast_moh_stop(p->owners[p->callwaitindex]->bridge);
2015                                         } else if (p->thirdcallindex == -1) {
2016                                                 if (p->threewaycalling) {
2017                                                         if ((ast->_state == AST_STATE_RINGING) ||
2018                                                                         (ast->_state == AST_STATE_UP) ||
2019                                                                         (ast->_state == AST_STATE_RING)) {
2020                                                                 if (!alloc_pseudo(p)) {
2021                                                                         /* Start three way call */
2022                                                                         /* Disable echo canceller for better dialing */
2023                                                                         zt_disable_ec(p);
2024                                                                         res = tone_zone_play_tone(zap_fd(p->z), ZT_TONE_DIALRECALL);
2025                                                                         if (res)
2026                                                                                 ast_log(LOG_WARNING, "Unable to start dial recall tone on channel %d\n", p->channel);
2027                                                                         chan = zt_new(p, AST_STATE_RESERVED,0,0,1);
2028                                                                         p->owner = chan;
2029                                                                         if (pthread_create(&threadid, &attr, ss_thread, chan)) {
2030                                                                                 ast_log(LOG_WARNING, "Unable to start simple switch on channel %d\n", p->channel);
2031                                                                                 res = tone_zone_play_tone(zap_fd(p->z), ZT_TONE_CONGESTION);
2032                                                                                 zt_enable_ec(p);
2033                                                                                 ast_hangup(chan);
2034                                                                         } else {
2035                                                                                 if (option_verbose > 2) 
2036                                                                                         ast_verbose(VERBOSE_PREFIX_3 "Started three way call on channel %d (index %d)\n", p->channel, p->thirdcallindex);
2037                                                                                 conf_clear(p);
2038                                                                                 /* Start music on hold if appropriate */
2039                                                                                 if (p->owners[p->normalindex]->bridge)
2040                                                                                                 ast_moh_start(p->owners[p->normalindex]->bridge, NULL);
2041                                                                         }               
2042                                                                 } else
2043                                                                         ast_log(LOG_WARNING, "Unable to allocate pseudo channel\n");
2044                                                         } else 
2045                                                                 ast_log(LOG_DEBUG, "Flash when call not up or ringing\n");
2046                                                 }
2047                                         } else {
2048                                                 if (option_debug)
2049                                                         ast_log(LOG_DEBUG, "Got flash with three way call up, dropping last call %d\n",
2050                                                                 p->thirdcallindex);
2051                                                 /* Drop the last call and stop the conference */
2052                                                 if (option_verbose > 2)
2053                                                         ast_verbose(VERBOSE_PREFIX_3 "Dropping three-way call on %s\n", p->owners[p->thirdcallindex]->name);
2054                                                 p->owners[p->thirdcallindex]->_softhangup |= AST_SOFTHANGUP_DEV;
2055                                                 conf_clear(p);
2056                                         }
2057                                 } else if (index == p->callwaitindex) {
2058                                         if (p->normalindex > -1) {
2059                                                 p->owner = p->owners[p->normalindex];
2060                                                 p->callwaitingrepeat = 0;
2061                                                 conf_clear(p);
2062                                                 /* Start music on hold if appropriate */
2063                                                 if (p->owners[p->callwaitindex]->bridge)
2064                                                                 ast_moh_start(p->owners[p->callwaitindex]->bridge, NULL);
2065                                                 if (p->owners[p->normalindex]->bridge)
2066                                                                 ast_moh_stop(p->owners[p->normalindex]->bridge);
2067                                         } else
2068                                                 ast_log(LOG_WARNING, "Wink/Flash on call wait, with no normal channel to flash to on channel %d?\n", p->channel);
2069                                 } else if (index == p->thirdcallindex) {
2070                                         if (p->normalindex > -1) {
2071                                                 /* One way or another, cancel music on hold */
2072                                                 if (p->owners[p->normalindex]->bridge)
2073                                                                 ast_moh_stop(p->owners[p->normalindex]->bridge);
2074                                                 if ((ast->_state != AST_STATE_RINGING) && (ast->_state != AST_STATE_UP) && (ast->_state != AST_STATE_RING)) {
2075                                                         tone_zone_play_tone(zap_fd(p->z), -1);
2076                                                         p->owner = p->owners[p->normalindex];
2077                                                         ast_log(LOG_DEBUG, "Dumping incomplete three way call in state %d\n", ast->_state);
2078                                                         zt_enable_ec(p);
2079                                                         return NULL;
2080                                                 }
2081                                                 p->owner = p->owners[p->normalindex];
2082                                                 p->owners[p->thirdcallindex]->fds[0] = zap_fd(p->pseudo);
2083                                                 p->callwaitingrepeat = 0;
2084                                                 if (p->owners[p->thirdcallindex]->_state == AST_STATE_RINGING) {
2085                                                         /* If we were ringing, stop the ringing on the main line and start it on
2086                                                            the pseudo */
2087                                                         tone_zone_play_tone(zap_fd(p->z), -1);
2088                                                         tone_zone_play_tone(zap_fd(p->pseudo), ZT_TONE_RINGTONE);
2089                                                 }
2090                                                 three_way(p);
2091                                                 /* Restart the echo canceller */
2092                                                 zt_enable_ec(p);
2093                                                 if (option_verbose > 2)
2094                                                         ast_verbose(VERBOSE_PREFIX_3 "Established 3-way conference between %s and %s\n", 
2095                                                                                 p->owners[p->normalindex]->name, p->owners[p->thirdcallindex]->name);
2096                                         } else {
2097                                                 ast_log(LOG_WARNING, "Wink/Flash on threeway call, with no normal channel to flash to on channel %d?\n", p->channel);
2098                                                 return NULL;
2099                                         }
2100                                 }
2101                                 break;
2102                         case SIG_EM:
2103                         case SIG_EMWINK:
2104                         case SIG_FEATD:
2105                         case SIG_FXSLS:
2106                         case SIG_FXSGS:
2107                                 if (p->dialing)
2108                                         ast_log(LOG_DEBUG, "Ignoring wink on channel %d\n", p->channel);
2109                                 else
2110                                         ast_log(LOG_DEBUG, "Got wink in weird state %d on channel %d\n", ast->_state, p->channel);
2111                                 break;
2112                         case SIG_FEATDMF:
2113                         case SIG_FEATB:
2114                                 /* FGD MF *Must* wait for wink */
2115                                 res = ioctl(zap_fd(p->z), ZT_DIAL, &p->dop);
2116                                 if (res < 0) {
2117                                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
2118                                         p->dop.dialstr[0] = '\0';
2119                                         return NULL;
2120                                 } else 
2121                                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
2122                                 p->dop.dialstr[0] = '\0';
2123                                 break;
2124                         default:
2125                                 ast_log(LOG_WARNING, "Don't know how to handle ring/off hoook for signalling %d\n", p->sig);
2126                         }
2127                         break;
2128                 case ZT_EVENT_HOOKCOMPLETE:
2129                         if (p->inalarm) break;
2130                         switch(p->sig) {
2131                         case SIG_FXSLS:  /* only interesting for FXS */
2132                         case SIG_FXSGS:
2133                         case SIG_FXSKS:
2134                         case SIG_EM:
2135                         case SIG_EMWINK:
2136                         case SIG_FEATD:
2137                                 res = ioctl(zap_fd(p->z), ZT_DIAL, &p->dop);
2138                                 if (res < 0) {
2139                                         ast_log(LOG_WARNING, "Unable to initiate dialing on trunk channel %d\n", p->channel);
2140                                         p->dop.dialstr[0] = '\0';
2141                                         return NULL;
2142                                 } else 
2143                                         ast_log(LOG_DEBUG, "Sent deferred digit string: %s\n", p->dop.dialstr);
2144                                 p->dop.dialstr[0] = '\0';
2145                                 break;
2146                         case SIG_FEATDMF:
2147                         case SIG_FEATB:
2148                                 ast_log(LOG_DEBUG, "Got hook complete in MF FGD, waiting for wink now on channel %d\n",p->channel);
2149                                 break;
2150                         default:
2151                                 break;
2152                         }
2153                         break;
2154                 default:
2155                         ast_log(LOG_DEBUG, "Dunno what to do with event %d on channel %d\n", res, p->channel);
2156         }
2157         return &p->f[index];
2158  }
2159
2160 struct ast_frame *zt_exception(struct ast_channel *ast)
2161 {
2162         struct zt_pvt *p = ast->pvt->pvt;
2163         int res;
2164         int usedindex=-1;
2165         int index;
2166         
2167         index = zt_get_index(ast, p, 1);
2168         
2169         p->f[index].frametype = AST_FRAME_NULL;
2170         p->f[index].datalen = 0;
2171         p->f[index].timelen = 0;
2172         p->f[index].mallocd = 0;
2173         p->f[index].offset = 0;
2174         p->f[index].subclass = 0;
2175         p->f[index].src = "zt_exception";
2176         p->f[index].data = NULL;
2177                 
2178         if ((p->owner != p->owners[0]) && 
2179             (p->owner != p->owners[1]) &&
2180                 (p->owner != p->owners[2])) {
2181                 /* If nobody owns us, absorb the event appropriately, otherwise
2182                    we loop indefinitely.  This occurs when, during call waiting, the
2183                    other end hangs up our channel so that it no longer exists, but we
2184                    have neither FLASH'd nor ONHOOK'd to signify our desire to
2185                    change to the other channel. */
2186                 res = zt_get_event(zap_fd(p->z));
2187                 if ((p->callwaitindex > -1) && (p->normalindex > -1)) 
2188                         ast_log(LOG_WARNING, "Absorbing exception on unowned channel, but there is both a normal and call waiting call still here?\n");
2189                 if (p->callwaitindex > -1) {
2190                         tone_zone_play_tone(zap_fd(p->z), -1);
2191                         p->owner = p->owners[p->callwaitindex];
2192                         usedindex = p->callwaitindex;
2193                 } else if (p->normalindex > -1) {
2194                         tone_zone_play_tone(zap_fd(p->z), -1);
2195                         p->owner = p->owners[p->normalindex];
2196                         usedindex = p->normalindex;
2197                 } else {
2198                         ast_log(LOG_WARNING, "No call wait call, no normal call, what do I do?\n");
2199                         return NULL;
2200                 }
2201                 switch(res) {
2202                 case ZT_EVENT_ONHOOK:
2203                         zt_disable_ec(p);
2204                         if (p->owner) {
2205                                 if (option_verbose > 2) 
2206                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %s still has call, ringing phone\n", p->owner->name);
2207                                 zt_ring_phone(p);
2208                                 p->callwaitingrepeat = 0;
2209                         } else
2210                                 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
2211                         break;
2212                 case ZT_EVENT_WINKFLASH:
2213                         if (p->owner) {
2214                                 if (option_verbose > 2) 
2215                                         ast_verbose(VERBOSE_PREFIX_3 "Channel %d flashed to other channel %s\n", p->channel, p->owner->name);
2216                                 if ((usedindex == p->callwaitindex) && (p->owner->_state == AST_STATE_RINGING)) {
2217                                         /* Answer the call wait if necessary */
2218                                         p->needanswer[usedindex] = 1;
2219                                         ast_setstate(p->owner, AST_STATE_UP);
2220                                 }
2221                                 p->callwaitingrepeat = 0;
2222                                 if (p->owner->bridge)
2223                                                 ast_moh_stop(p->owner->bridge);
2224                         } else
2225                                 ast_log(LOG_WARNING, "Absorbed on hook, but nobody is left!?!?\n");
2226                         break;
2227                 default:
2228                         ast_log(LOG_WARNING, "Don't know how to absorb event %s\n", event2str(res));
2229                 }
2230                 return &p->f[index];
2231         }
2232         /* If it's not us, return NULL immediately */
2233         if (ast != p->owner)
2234                 return &p->f[index];
2235
2236         return zt_handle_event(ast);
2237 }
2238
2239 struct ast_frame  *zt_read(struct ast_channel *ast)
2240 {
2241         struct zt_pvt *p = ast->pvt->pvt;
2242         int res;
2243         int index;
2244         int *linear;
2245         ZAP *z = NULL;
2246         void *readbuf;
2247         
2248         ast_pthread_mutex_lock(&p->lock);
2249         
2250         index = zt_get_index(ast, p, 0);
2251         
2252         p->f[index].frametype = AST_FRAME_NULL;
2253         p->f[index].datalen = 0;
2254         p->f[index].timelen = 0;
2255         p->f[index].mallocd = 0;
2256         p->f[index].offset = 0;
2257         p->f[index].subclass = 0;
2258         p->f[index].src = "zt_read";
2259         p->f[index].data = NULL;
2260         
2261         /* Hang up if we don't really exist */
2262         if (index < 0)  {
2263                 ast_log(LOG_WARNING, "We dont exist?\n");
2264                 pthread_mutex_unlock(&p->lock);
2265                 return NULL;
2266         }
2267         
2268         if (p->ringt == 1) {
2269                 pthread_mutex_unlock(&p->lock);
2270                 return NULL;
2271         }
2272         else if (p->ringt > 0) 
2273                 p->ringt--;
2274
2275         if (p->needringing[index]) {
2276                 /* Send ringing frame if requested */
2277                 p->needringing[index] = 0;
2278                 p->f[index].frametype = AST_FRAME_CONTROL;
2279                 p->f[index].subclass = AST_CONTROL_RINGING;
2280                 ast_setstate(ast, AST_STATE_RINGING);
2281                 pthread_mutex_unlock(&p->lock);
2282                 return &p->f[index];
2283         }       
2284         
2285         if (p->needanswer[index]) {
2286                 /* Send ringing frame if requested */
2287                 p->needanswer[index] = 0;
2288                 p->f[index].frametype = AST_FRAME_CONTROL;
2289                 p->f[index].subclass = AST_CONTROL_ANSWER;
2290                 ast_setstate(ast, AST_STATE_UP);
2291                 pthread_mutex_unlock(&p->lock);
2292                 return &p->f[index];
2293         }       
2294         
2295         if (ast != p->owner) {
2296                 /* If it's not us.  If this isn't a three way call, return immediately */
2297                 if (!INTHREEWAY(p)) {
2298                         pthread_mutex_unlock(&p->lock);
2299                         return &p->f[index];
2300                 }
2301                 /* If it's not the third call, return immediately */
2302                 if (ast != p->owners[p->thirdcallindex]) {
2303                         pthread_mutex_unlock(&p->lock);
2304                         return &p->f[index];
2305                 }
2306                 if (!p->pseudo) 
2307                         ast_log(LOG_ERROR, "No pseudo channel\n");
2308                 z = p->pseudo;  
2309                 linear = &p->pseudolinear;
2310         } else {
2311                 z = p->z;
2312                 linear = &p->reallinear;
2313         }
2314
2315         if (!z) {
2316                 ast_log(LOG_WARNING, "No zap structure?!?\n");
2317                 pthread_mutex_unlock(&p->lock);
2318                 return NULL;
2319         }
2320         
2321         /* Check first for any outstanding DTMF characters */
2322         if (strlen(p->dtmfq)) {
2323                 p->f[index].subclass = p->dtmfq[0];
2324                 memmove(p->dtmfq, p->dtmfq + 1, sizeof(p->dtmfq) - 1);
2325                 p->f[index].frametype = AST_FRAME_DTMF;
2326                 if (p->confirmanswer) {
2327                         printf("Confirm answer!\n");
2328                         /* Upon receiving a DTMF digit, consider this an answer confirmation instead
2329                            of a DTMF digit */
2330                         p->f[index].frametype = AST_FRAME_CONTROL;
2331                         p->f[index].subclass = AST_CONTROL_ANSWER;
2332                         ast_setstate(ast, AST_STATE_UP);
2333                 }
2334                 pthread_mutex_unlock(&p->lock);
2335                 return &p->f[index];
2336         }
2337         
2338         if (ast->pvt->rawreadformat == AST_FORMAT_SLINEAR) {
2339                 if (!*linear) {
2340                         *linear = 1;
2341                         res = zap_setlinear(p->z, *linear);
2342                         if (res) 
2343                                 ast_log(LOG_WARNING, "Unable to set channel %d to linear mode.\n", p->channel);
2344                 }
2345         } else if ((ast->pvt->rawreadformat == AST_FORMAT_ULAW) ||
2346                    (ast->pvt->rawreadformat == AST_FORMAT_ALAW)) {
2347                 if (*linear) {
2348                         *linear = 0;
2349                         res = zap_setlinear(p->z, *linear);
2350                         if (res) 
2351                                 ast_log(LOG_WARNING, "Unable to set channel %d to linear mode.\n", p->channel);
2352                 }
2353         } else {
2354                 ast_log(LOG_WARNING, "Don't know how to read frames in format %d\n", ast->pvt->rawreadformat);
2355                 pthread_mutex_unlock(&p->lock);
2356                 return NULL;
2357         }
2358         readbuf = ((unsigned char *)p->buffer[index]) + AST_FRIENDLY_OFFSET;
2359         CHECK_BLOCKING(ast);
2360         if ((z != p->z) && (z != p->pseudo)) {
2361                 pthread_mutex_unlock(&p->lock);
2362                 return NULL;
2363         }
2364         res = zap_recchunk(z, readbuf, READ_SIZE, ((p->ignoredtmf) ? 0 : ZAP_DTMFINT));
2365         ast->blocking = 0;
2366         /* Check for hangup */
2367         if (res < 0) {
2368                 if (res == -1) 
2369                         ast_log(LOG_WARNING, "zt_rec: %s\n", strerror(errno));
2370                 pthread_mutex_unlock(&p->lock);
2371                 return NULL;
2372         }
2373         if (res != READ_SIZE) {
2374                 if (option_debug)
2375                         ast_log(LOG_DEBUG, "Short read, must be DTMF or something...\n");
2376                 /* XXX UGLY!!  Zapata's DTMF handling is a bit ugly XXX */
2377                 if (zap_dtmfwaiting(z) && !strlen(zap_dtmfbuf(z))) {
2378                         zap_getdtmf(z, 1, NULL, 0, 1, 1, 0);
2379                 }
2380                 if (strlen(zap_dtmfbuf(z))) {
2381                         if (p->confirmanswer) {
2382                                 printf("Confirm answer!\n");
2383                                 /* Upon receiving a DTMF digit, consider this an answer confirmation instead
2384                                    of a DTMF digit */
2385                                 p->f[index].frametype = AST_FRAME_CONTROL;
2386                                 p->f[index].subclass = AST_CONTROL_ANSWER;
2387                                 ast_setstate(ast, AST_STATE_UP);
2388                         } else {
2389                                 ast_log(LOG_DEBUG, "Got some dtmf ('%s')... on channel %s\n", zap_dtmfbuf(z), ast->name);
2390                                 /* DTMF tone detected.  Queue and erturn */
2391                                 if (p->callwaitcas) {
2392                                         if (!strcmp(zap_dtmfbuf(z), "A") || !strcmp(zap_dtmfbuf(z), "D")) {
2393                                                 ast_log(LOG_DEBUG, "Got some DTMF, but it's for the CAS\n");
2394                                                 if (p->cidspill)
2395                                                         free(p->cidspill);
2396                                                 send_cwcidspill(p);
2397                                         }
2398                                         /* Return NULL */
2399                                         pthread_mutex_unlock(&p->lock);
2400                                         return &p->f[index];
2401                                 } else {
2402                                         strncpy(p->dtmfq + strlen(p->dtmfq), zap_dtmfbuf(z), sizeof(p->dtmfq) - strlen(p->dtmfq)-1);
2403                                         zap_clrdtmfn(z);
2404                                 }
2405                         }
2406                 } else {
2407                         pthread_mutex_unlock(&p->lock);
2408                         return zt_handle_event(ast);
2409                 }
2410                 if (strlen(p->dtmfq)) {
2411                         p->f[index].subclass = p->dtmfq[0];
2412                         memmove(p->dtmfq, p->dtmfq + 1, sizeof(p->dtmfq) - 1);
2413                         p->f[index].frametype = AST_FRAME_DTMF;
2414                 }
2415                 pthread_mutex_unlock(&p->lock);
2416                 return &p->f[index];
2417         }
2418         if (p->tdd) { /* if in TDD mode, see if we receive that */
2419                 int c;
2420
2421                 c = tdd_feed(p->tdd,readbuf,READ_SIZE);
2422                 if (c < 0) {
2423                         ast_log(LOG_DEBUG,"tdd_feed failed\n");
2424                         return NULL;
2425                 }
2426                 if (c) { /* if a char to return */
2427                         p->f[index].subclass = 0;
2428                         p->f[index].frametype = AST_FRAME_TEXT;
2429                         p->f[index].mallocd = 0;
2430                         p->f[index].offset = AST_FRIENDLY_OFFSET;
2431                         p->f[index].data = p->buffer[index] + AST_FRIENDLY_OFFSET;
2432                         p->f[index].datalen = 1;
2433                         *((char *) p->f[index].data) = c;
2434                         pthread_mutex_unlock(&p->lock);
2435                         return &p->f[index];
2436                 }
2437         }
2438         if (p->callwaitingrepeat)
2439                 p->callwaitingrepeat--;
2440         /* Repeat callwaiting */
2441         if (p->callwaitingrepeat == 1) {
2442                 p->callwaitrings++;
2443                 zt_callwait(ast);
2444         }
2445         if (ast->pvt->rawreadformat == AST_FORMAT_SLINEAR) {
2446                 p->f[index].datalen = READ_SIZE * 2;
2447         } else 
2448                 p->f[index].datalen = READ_SIZE;
2449
2450         /* Handle CallerID Transmission */
2451         if (p->cidspill &&((ast->_state == AST_STATE_UP) || (ast->rings == p->cidrings))) {
2452                 send_callerid(p);
2453         }
2454
2455         p->f[index].frametype = AST_FRAME_VOICE;
2456         p->f[index].subclass = ast->pvt->rawreadformat;
2457         p->f[index].timelen = READ_SIZE/8;
2458         p->f[index].mallocd = 0;
2459         p->f[index].offset = AST_FRIENDLY_OFFSET;
2460         p->f[index].data = p->buffer[index] + AST_FRIENDLY_OFFSET/2;
2461 #if 0
2462         ast_log(LOG_DEBUG, "Read %d of voice on %s\n", p->f[index].datalen, ast->name);
2463 #endif  
2464         if (p->dialing) {
2465                 /* Whoops, we're still dialing, don't send anything */
2466                 p->f[index].frametype = AST_FRAME_NULL;
2467                 p->f[index].subclass = 0;
2468                 p->f[index].timelen = 0;
2469                 p->f[index].mallocd = 0;
2470                 p->f[index].offset = 0;
2471                 p->f[index].data = NULL;
2472                 p->f[index].datalen= 0;
2473         }
2474         pthread_mutex_unlock(&p->lock);
2475         return &p->f[index];
2476 }
2477
2478 static int my_zt_write(struct zt_pvt *p, unsigned char *buf, int len, int threeway)
2479 {
2480         int sent=0;
2481         int size;
2482         int res;
2483         int fd;
2484         if (threeway) 
2485                 fd = zap_fd(p->pseudo);
2486         else
2487                 fd = zap_fd(p->z);
2488         while(len) {
2489                 size = len;
2490                 if (size > READ_SIZE)
2491                         size = READ_SIZE;
2492                 res = write(fd, buf, size);
2493                 if (res != size) {
2494                         if (option_debug)
2495                                 ast_log(LOG_DEBUG, "Write returned %d (%s) on channel %d\n", res, strerror(errno), p->channel);
2496                         return sent;
2497                 }
2498                 len -= size;
2499                 buf += size;
2500         }
2501         return sent;
2502 }
2503
2504 static int zt_write(struct ast_channel *ast, struct ast_frame *frame)
2505 {
2506         struct zt_pvt *p = ast->pvt->pvt;
2507         int res;
2508         unsigned char outbuf[4096];
2509         
2510         if (ast != p->owner) {
2511                 /* If it's not us.  If this isn't a three way call, return immediately */
2512                 if (!INTHREEWAY(p)) {
2513                         return 0;
2514                 }
2515                 /* If it's not the third call, return immediately */
2516                 if (ast != p->owners[p->thirdcallindex]) {
2517                         return 0;
2518                 }
2519         }
2520         
2521         /* Write a frame of (presumably voice) data */
2522         if (frame->frametype != AST_FRAME_VOICE) {
2523                 if (frame->frametype != AST_FRAME_IMAGE)
2524                         ast_log(LOG_WARNING, "Don't know what to do with frame type '%d'\n", frame->frametype);
2525                 return 0;
2526         }
2527         if ((frame->subclass != AST_FORMAT_SLINEAR) && 
2528             (frame->subclass != AST_FORMAT_ULAW) &&
2529             (frame->subclass != AST_FORMAT_ALAW)) {
2530                 ast_log(LOG_WARNING, "Cannot handle frames in %d format\n", frame->subclass);
2531                 return -1;
2532         }
2533         if (p->dialing) {
2534                 if (option_debug)
2535                         ast_log(LOG_DEBUG, "Dropping frame since I'm still dialing on %s...\n",ast->name);
2536                 return 0;
2537         }
2538         if (p->cidspill) {
2539                 if (option_debug)
2540                         ast_log(LOG_DEBUG, "Dropping frame since I've still got a callerid spill\n");
2541                 return 0;
2542         }
2543         /* Return if it's not valid data */
2544         if (!frame->data || !frame->datalen)
2545                 return 0;
2546         if (frame->datalen > sizeof(outbuf) * 2) {
2547                 ast_log(LOG_WARNING, "Frame too large\n");
2548                 return 0;
2549         }
2550         if (frame->subclass == AST_FORMAT_SLINEAR) {
2551                 if (ast == p->owner) {
2552                         if (!p->reallinear) {
2553                                 p->reallinear = 1;
2554                                 res = zap_setlinear(p->z, p->reallinear);
2555                                 if (res)
2556                                         ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
2557                         }
2558                 } else {
2559                         if (!p->pseudolinear) {
2560                                 p->pseudolinear = 1;
2561                                 res = zap_setlinear(p->pseudo, p->pseudolinear);
2562                                 if (res)
2563                                         ast_log(LOG_WARNING, "Unable to set linear mode on channel %d (pseudo)\n", p->channel);
2564                         }
2565                 }
2566                 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, (ast != p->owner));
2567         } else {
2568                 /* x-law already */
2569                 if (ast == p->owner) {
2570                         if (p->reallinear) {
2571                                 p->reallinear = 0;
2572                                 res = zap_setlinear(p->z, p->reallinear);
2573                                 if (res)
2574                                         ast_log(LOG_WARNING, "Unable to set linear mode on channel %d\n", p->channel);
2575                         }
2576                 } else {
2577                         if (p->pseudolinear) {
2578                                 p->pseudolinear = 0;
2579                                 res = zap_setlinear(p->pseudo, p->pseudolinear);
2580                                 if (res)
2581                                         ast_log(LOG_WARNING, "Unable to set linear mode on channel %d (pseudo)\n", p->channel);
2582                         }
2583                 }
2584                 res = my_zt_write(p, (unsigned char *)frame->data, frame->datalen, (ast != p->owner));
2585         }
2586         if (res < 0) {
2587                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
2588                 return -1;
2589         } 
2590         return 0;
2591 }
2592
2593 static int zt_indicate(struct ast_channel *chan, int condition)
2594 {
2595         struct zt_pvt *p = chan->pvt->pvt;
2596         int res=-1;
2597         switch(condition) {
2598         case AST_CONTROL_BUSY:
2599                 res = tone_zone_play_tone(zap_fd(p->z), ZT_TONE_BUSY);
2600                 break;
2601         case AST_CONTROL_RINGING:
2602                 res = tone_zone_play_tone(zap_fd(p->z), ZT_TONE_RINGTONE);
2603                 if (chan->_state != AST_STATE_UP) {
2604                         if ((chan->_state != AST_STATE_RING) ||
2605                                 ((p->sig != SIG_FXSKS) &&
2606                                  (p->sig != SIG_FXSLS) &&
2607                                  (p->sig != SIG_FXSGS)))
2608                                 ast_setstate(chan, AST_STATE_RINGING);
2609                 }
2610                 break;
2611         case AST_CONTROL_CONGESTION:
2612                 res = tone_zone_play_tone(zap_fd(p->z), ZT_TONE_CONGESTION);
2613                 break;
2614         case -1:
2615                 res = tone_zone_play_tone(zap_fd(p->z), -1);
2616                 break;
2617         default:
2618                 ast_log(LOG_WARNING, "Don't know how to set condition %d on channel %s\n", condition, chan->name);
2619         }
2620         return res;
2621 }
2622
2623 static struct ast_channel *zt_new(struct zt_pvt *i, int state, int startpbx, int callwaiting, int thirdcall)
2624 {
2625         struct ast_channel *tmp;
2626         int x;
2627         int deflaw;
2628         int res;
2629         ZT_PARAMS ps;
2630         for (x=0;x<3;x++)
2631                 if (!i->owners[x])
2632                         break;
2633         if (x > 2) {
2634                 ast_log(LOG_WARNING, "No available owner slots\n");
2635                 return NULL;
2636         }
2637         tmp = ast_channel_alloc(0);
2638         if (tmp) {
2639                 ps.channo = i->channel;
2640                 res = ioctl(zap_fd(i->z), ZT_GET_PARAMS, &ps);
2641                 if (res) {
2642                         ast_log(LOG_WARNING, "Unable to get parameters, assuming MULAW\n");
2643                         ps.curlaw = ZT_LAW_MULAW;
2644                 }
2645                 if (ps.curlaw == ZT_LAW_ALAW)
2646                         deflaw = AST_FORMAT_ALAW;
2647                 else
2648                         deflaw = AST_FORMAT_ULAW;
2649                 snprintf(tmp->name, sizeof(tmp->name), "Zap/%d-%d", i->channel, x + 1);
2650                 tmp->type = type;
2651                 tmp->fds[0] = zap_fd(i->z);
2652                 
2653                 tmp->nativeformats = AST_FORMAT_SLINEAR | deflaw;
2654                 
2655                 /* Start out assuming ulaw since it's smaller :) */
2656                 tmp->pvt->rawreadformat = deflaw;
2657                 tmp->readformat = deflaw;
2658                 tmp->pvt->rawwriteformat = deflaw;
2659                 tmp->writeformat = deflaw;
2660                 
2661                 if (state == AST_STATE_RING)
2662                         tmp->rings = 1;
2663                 tmp->pvt->pvt = i;
2664                 tmp->pvt->send_digit = zt_digit;
2665                 tmp->pvt->send_text = zt_sendtext;
2666                 tmp->pvt->call = zt_call;
2667                 tmp->pvt->hangup = zt_hangup;
2668                 tmp->pvt->answer = zt_answer;
2669                 tmp->pvt->read = zt_read;
2670                 tmp->pvt->write = zt_write;
2671                 tmp->pvt->bridge = zt_bridge;
2672                 tmp->pvt->exception = zt_exception;
2673                 tmp->pvt->indicate = zt_indicate;
2674                 tmp->pvt->fixup = zt_fixup;
2675                 tmp->pvt->setoption = zt_setoption;
2676                 if (strlen(i->language))
2677                         strncpy(tmp->language, i->language, sizeof(tmp->language)-1);
2678                 if (strlen(i->musicclass))
2679                         strncpy(tmp->musicclass, i->musicclass, sizeof(tmp->musicclass)-1);
2680                 /* Keep track of who owns it */
2681                 i->owners[x] = tmp;
2682                 if (!i->owner)
2683                         i->owner = tmp;
2684                 if (strlen(i->accountcode))
2685                         strncpy(tmp->accountcode, i->accountcode, sizeof(tmp->accountcode)-1);
2686                 if (i->amaflags)
2687                         tmp->amaflags = i->amaflags;
2688                 if (callwaiting) {
2689                         if (i->callwaitindex > -1)
2690                                 ast_log(LOG_WARNING, "channel %d already has a call wait call\n", i->channel);
2691                         i->callwaitindex = x;
2692                 } else if (thirdcall) {
2693                         if (i->thirdcallindex > -1)
2694                                 ast_log(LOG_WARNING, "channel %d already has a third call\n", i->channel);
2695                         i->thirdcallindex = x;
2696                 } else {
2697                         if (i->normalindex > -1) 
2698                                 ast_log(LOG_WARNING, "channel %d already has a normal call\n", i->channel);
2699                         i->normalindex = x;
2700                 }
2701                 ast_setstate(tmp, state);
2702                 ast_pthread_mutex_lock(&usecnt_lock);
2703                 usecnt++;
2704                 ast_pthread_mutex_unlock(&usecnt_lock);
2705                 ast_update_use_count();
2706                 strncpy(tmp->context, i->context, sizeof(tmp->context)-1);
2707                 /* Copy call forward info */
2708                 strncpy(tmp->call_forward, i->call_forward, sizeof(tmp->call_forward));
2709                 /* If we've been told "no ADSI" then enforce it */
2710                 if (!i->adsi)
2711                         tmp->adsicpe = AST_ADSI_UNAVAILABLE;
2712                 if (strlen(i->exten))
2713                         strncpy(tmp->exten, i->exten, sizeof(tmp->exten)-1);
2714                 if (strlen(i->callerid)) {
2715                         tmp->callerid = strdup(i->callerid);
2716                         tmp->ani = strdup(i->callerid);
2717                 }
2718 #ifdef ZAPATA_PRI
2719                 /* Assume calls are not idle calls unless we're told differently */
2720                 i->isidlecall = 0;
2721 #endif
2722                 if (startpbx) {
2723                         if (ast_pbx_start(tmp)) {
2724                                 ast_log(LOG_WARNING, "Unable to start PBX on %s\n", tmp->name);
2725                                 ast_hangup(tmp);
2726                                 tmp = NULL;
2727                         }
2728                 }
2729         } else
2730                 ast_log(LOG_WARNING, "Unable to allocate channel structure\n");
2731         return tmp;
2732 }
2733
2734
2735 static int bump_gains(struct zt_pvt *p)
2736 {
2737         int res;
2738         /* Bump receive gain by 9.0db */
2739         res = set_actual_gain(zap_fd(p->z), 0, p->rxgain + 5.0, p->txgain);
2740         if (res) {
2741                 ast_log(LOG_WARNING, "Unable to bump gain\n");
2742                 return -1;
2743         }
2744         return 0;
2745 }
2746
2747 static int restore_gains(struct zt_pvt *p)
2748 {
2749         int res;
2750         /* Bump receive gain by 9.0db */
2751         res = set_actual_gain(zap_fd(p->z), 0, p->rxgain, p->txgain);
2752         if (res) {
2753                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
2754                 return -1;
2755         }
2756         return 0;
2757 }
2758
2759 static void *ss_thread(void *data)
2760 {
2761         struct ast_channel *chan = data;
2762         struct zt_pvt *p = chan->pvt->pvt;
2763         char exten[AST_MAX_EXTENSION];
2764         char exten2[AST_MAX_EXTENSION];
2765         unsigned char buf[256];
2766         char cid[256];
2767         struct callerid_state *cs;
2768         char *name=NULL, *number=NULL;
2769         int flags;
2770         int i;
2771         int timeout;
2772         int getforward=0;
2773         char *s1, *s2;
2774         int len = 0;
2775         int res;
2776         if (option_verbose > 2) 
2777                 ast_verbose( VERBOSE_PREFIX_3 "Starting simple switch on '%s'\n", chan->name);
2778         zap_clrdtmf(p->z);
2779         switch(p->sig) {
2780         case SIG_FEATD:
2781         case SIG_FEATDMF:
2782         case SIG_FEATB:
2783         case SIG_EMWINK:
2784                 zap_wink(p->z);
2785                 /* Fall through */
2786         case SIG_EM:
2787                 res = tone_zone_play_tone(zap_fd(p->z), -1);
2788                 zap_clrdtmf(p->z);
2789                 /* set digit mode appropriately */
2790                 if ((p->sig == SIG_FEATDMF) || (p->sig == SIG_FEATB)) zap_digitmode(p->z,ZAP_MF); 
2791                 else zap_digitmode(p->z,ZAP_DTMF);
2792                 /* Wait for the first digit (up to 5 seconds). */
2793                 res = zap_getdtmf(p->z, 1, NULL, 0, 5000, 5000, ZAP_TIMEOUTOK | ZAP_HOOKEXIT);
2794
2795                 if (res == 1) {
2796                         switch(p->sig)
2797                         {
2798                             case SIG_FEATD:
2799                                 res = zap_getdtmf(p->z, 50, "*", 0, 3000, 15000, ZAP_HOOK