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