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