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