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