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