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