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