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