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