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