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