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