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