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