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