cbd1bf20153d812c7fe71c9331f9993c4ae489c0
[asterisk/asterisk.git] / channels / chan_dahdi.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief DAHDI for Pseudo TDM
22  *
23  * \author Mark Spencer <markster@digium.com>
24  * 
25  * Connects to the DAHDI telephony library as well as 
26  * libpri. Libpri is optional and needed only if you are
27  * going to use ISDN connections.
28  *
29  * You need to install libraries before you attempt to compile
30  * and install the DAHDI channel.
31  *
32  * \par See also
33  * \arg \ref Config_dahdi
34  *
35  * \ingroup channel_drivers
36  *
37  * \todo Deprecate the "musiconhold" configuration option post 1.4
38  */
39
40 /*** MODULEINFO
41         <depend>res_smdi</depend>
42         <depend>dahdi</depend>
43         <depend>tonezone</depend>
44         <use>pri</use>
45         <use>ss7</use>
46  ***/
47
48 #include "asterisk.h"
49
50 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
51
52 #ifdef __NetBSD__
53 #include <pthread.h>
54 #include <signal.h>
55 #else
56 #include <sys/signal.h>
57 #endif
58 #include <sys/ioctl.h>
59 #include <math.h>
60 #include <ctype.h>
61 #include "asterisk/dahdi.h"
62
63 #ifdef HAVE_PRI
64 #include <libpri.h>
65 #endif
66
67 #ifdef HAVE_SS7
68 #include <libss7.h>
69 #endif
70
71 #include "asterisk/lock.h"
72 #include "asterisk/channel.h"
73 #include "asterisk/config.h"
74 #include "asterisk/module.h"
75 #include "asterisk/pbx.h"
76 #include "asterisk/file.h"
77 #include "asterisk/ulaw.h"
78 #include "asterisk/alaw.h"
79 #include "asterisk/callerid.h"
80 #include "asterisk/adsi.h"
81 #include "asterisk/cli.h"
82 #include "asterisk/cdr.h"
83 #include "asterisk/features.h"
84 #include "asterisk/musiconhold.h"
85 #include "asterisk/say.h"
86 #include "asterisk/tdd.h"
87 #include "asterisk/app.h"
88 #include "asterisk/dsp.h"
89 #include "asterisk/astdb.h"
90 #include "asterisk/manager.h"
91 #include "asterisk/causes.h"
92 #include "asterisk/term.h"
93 #include "asterisk/utils.h"
94 #include "asterisk/transcap.h"
95 #include "asterisk/stringfields.h"
96 #include "asterisk/abstract_jb.h"
97 #include "asterisk/smdi.h"
98 #include "asterisk/astobj.h"
99 #include "asterisk/event.h"
100 #include "asterisk/devicestate.h"
101
102 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
103
104 #ifdef DAHDI_SPANINFO_HAS_LINECONFIG
105 static const char *lbostr[] = {
106 "0 db (CSU)/0-133 feet (DSX-1)",
107 "133-266 feet (DSX-1)",
108 "266-399 feet (DSX-1)",
109 "399-533 feet (DSX-1)",
110 "533-655 feet (DSX-1)",
111 "-7.5db (CSU)",
112 "-15db (CSU)",
113 "-22.5db (CSU)"
114 };
115 #endif
116
117 /*! Global jitterbuffer configuration - by default, jb is disabled */
118 static struct ast_jb_conf default_jbconf =
119 {
120         .flags = 0,
121         .max_size = -1,
122         .resync_threshold = -1,
123         .impl = ""
124 };
125 static struct ast_jb_conf global_jbconf;
126
127 #if !defined(DAHDI_SIG_EM_E1) || (defined(HAVE_PRI) && !defined(DAHDI_SIG_HARDHDLC))
128 #error "Your DAHDI is too old.  Please update"
129 #endif
130
131 #ifndef DAHDI_TONEDETECT
132 /* Work around older code with no tone detect */
133 #define DAHDI_EVENT_DTMFDOWN 0
134 #define DAHDI_EVENT_DTMFUP 0
135 #endif
136
137 /* define this to send PRI user-user information elements */
138 #undef SUPPORT_USERUSER
139
140 /*! 
141  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
142  * the user hangs up to reset the state machine so ring works properly.
143  * This is used to be able to support kewlstart by putting the zhone in
144  * groundstart mode since their forward disconnect supervision is entirely
145  * broken even though their documentation says it isn't and their support
146  * is entirely unwilling to provide any assistance with their channel banks
147  * even though their web site says they support their products for life.
148  */
149 /* #define ZHONE_HACK */
150
151 /*! \note
152  * Define if you want to check the hook state for an FXO (FXS signalled) interface
153  * before dialing on it.  Certain FXO interfaces always think they're out of
154  * service with this method however.
155  */
156 /* #define DAHDI_CHECK_HOOKSTATE */
157
158 /*! \brief Typically, how many rings before we should send Caller*ID */
159 #define DEFAULT_CIDRINGS 1
160
161 #define CHANNEL_PSEUDO -12
162
163 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
164
165
166 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
167 #define NEED_MFDETECT(p) (((p)->sig == SIG_FEATDMF) || ((p)->sig == SIG_FEATDMF_TA) || ((p)->sig == SIG_E911) || ((p)->sig == SIG_FGC_CAMA) || ((p)->sig == SIG_FGC_CAMAMF) || ((p)->sig == SIG_FEATB)) 
168
169 static const char tdesc[] = "DAHDI Telephony Driver"
170 #ifdef HAVE_PRI
171                " w/PRI"
172 #endif
173 #ifdef HAVE_SS7
174                " w/SS7"
175 #endif
176 ;
177
178 static const char config[] = "chan_dahdi.conf";
179
180 #define SIG_EM          DAHDI_SIG_EM
181 #define SIG_EMWINK      (0x0100000 | DAHDI_SIG_EM)
182 #define SIG_FEATD       (0x0200000 | DAHDI_SIG_EM)
183 #define SIG_FEATDMF     (0x0400000 | DAHDI_SIG_EM)
184 #define SIG_FEATB       (0x0800000 | DAHDI_SIG_EM)
185 #define SIG_E911        (0x1000000 | DAHDI_SIG_EM)
186 #define SIG_FEATDMF_TA  (0x2000000 | DAHDI_SIG_EM)
187 #define SIG_FGC_CAMA    (0x4000000 | DAHDI_SIG_EM)
188 #define SIG_FGC_CAMAMF  (0x8000000 | DAHDI_SIG_EM)
189 #define SIG_FXSLS       DAHDI_SIG_FXSLS
190 #define SIG_FXSGS       DAHDI_SIG_FXSGS
191 #define SIG_FXSKS       DAHDI_SIG_FXSKS
192 #define SIG_FXOLS       DAHDI_SIG_FXOLS
193 #define SIG_FXOGS       DAHDI_SIG_FXOGS
194 #define SIG_FXOKS       DAHDI_SIG_FXOKS
195 #define SIG_PRI         DAHDI_SIG_CLEAR
196 #define SIG_BRI         (0x2000000 | DAHDI_SIG_CLEAR)
197 #define SIG_BRI_PTMP    (0X4000000 | DAHDI_SIG_CLEAR)
198 #define SIG_SS7         (0x1000000 | DAHDI_SIG_CLEAR)
199 #define SIG_SF          DAHDI_SIG_SF
200 #define SIG_SFWINK      (0x0100000 | DAHDI_SIG_SF)
201 #define SIG_SF_FEATD    (0x0200000 | DAHDI_SIG_SF)
202 #define SIG_SF_FEATDMF  (0x0400000 | DAHDI_SIG_SF)
203 #define SIG_SF_FEATB    (0x0800000 | DAHDI_SIG_SF)
204 #define SIG_EM_E1       DAHDI_SIG_EM_E1
205 #define SIG_GR303FXOKS  (0x0100000 | DAHDI_SIG_FXOKS)
206 #define SIG_GR303FXSKS  (0x0100000 | DAHDI_SIG_FXSKS)
207
208 #ifdef LOTS_OF_SPANS
209 #define NUM_SPANS       DAHDI_MAX_SPANS
210 #else
211 #define NUM_SPANS               32
212 #endif
213 #define NUM_DCHANS              4       /*!< No more than 4 d-channels */
214 #define MAX_CHANNELS    672             /*!< No more than a DS3 per trunk group */
215
216 #define CHAN_PSEUDO     -2
217
218 #define DCHAN_PROVISIONED (1 << 0)
219 #define DCHAN_NOTINALARM  (1 << 1)
220 #define DCHAN_UP          (1 << 2)
221
222 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
223
224 /* Overlap dialing option types */
225 #define DAHDI_OVERLAPDIAL_NONE 0
226 #define DAHDI_OVERLAPDIAL_OUTGOING 1
227 #define DAHDI_OVERLAPDIAL_INCOMING 2
228 #define DAHDI_OVERLAPDIAL_BOTH (DAHDI_OVERLAPDIAL_INCOMING|DAHDI_OVERLAPDIAL_OUTGOING)
229
230
231 #define CALLPROGRESS_PROGRESS           1
232 #define CALLPROGRESS_FAX_OUTGOING       2
233 #define CALLPROGRESS_FAX_INCOMING       4
234 #define CALLPROGRESS_FAX                (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
235
236 static char defaultcic[64] = "";
237 static char defaultozz[64] = "";
238
239 static char parkinglot[AST_MAX_EXTENSION] = "";         /*!< Default parking lot for this channel */
240
241 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
242 static char mwimonitornotify[PATH_MAX] = "";
243
244 static char progzone[10] = "";
245
246 static int usedistinctiveringdetection = 0;
247 static int distinctiveringaftercid = 0;
248
249 static int numbufs = 4;
250
251 static int mwilevel = 512;
252
253 #ifdef HAVE_PRI
254 static struct ast_channel inuse;
255 #ifdef PRI_GETSET_TIMERS
256 static int pritimers[PRI_MAX_TIMERS];
257 #endif
258 static int pridebugfd = -1;
259 static char pridebugfilename[1024] = "";
260 #endif
261
262 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
263 static int firstdigittimeout = 16000;
264
265 /*! \brief How long to wait for following digits (FXO logic) */
266 static int gendigittimeout = 8000;
267
268 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
269 static int matchdigittimeout = 3000;
270
271 /*! \brief Protect the interface list (of dahdi_pvt's) */
272 AST_MUTEX_DEFINE_STATIC(iflock);
273
274
275 static int ifcount = 0;
276
277 #ifdef HAVE_PRI
278 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
279 #endif
280
281 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
282    when it's doing something critical. */
283 AST_MUTEX_DEFINE_STATIC(monlock);
284
285 /*! \brief This is the thread for the monitor which checks for input on the channels
286    which are not currently in use. */
287 static pthread_t monitor_thread = AST_PTHREADT_NULL;
288
289 static int restart_monitor(void);
290
291 static enum ast_bridge_result dahdi_bridge(struct ast_channel *c0, struct ast_channel *c1, int flags, struct ast_frame **fo, struct ast_channel **rc, int timeoutms);
292
293 static int dahdi_sendtext(struct ast_channel *c, const char *text);
294
295 static void mwi_event_cb(const struct ast_event *event, void *userdata)
296 {
297         /* This module does not handle MWI in an event-based manner.  However, it
298          * subscribes to MWI for each mailbox that is configured so that the core
299          * knows that we care about it.  Then, chan_dahdi will get the MWI from the
300          * event cache instead of checking the mailbox directly. */
301 }
302
303 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
304 static inline int dahdi_get_event(int fd)
305 {
306         int j;
307         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
308                 return -1;
309         return j;
310 }
311
312 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
313 static inline int dahdi_wait_event(int fd)
314 {
315         int i, j = 0;
316         i = DAHDI_IOMUX_SIGEVENT;
317         if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
318                 return -1;
319         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
320                 return -1;
321         return j;
322 }
323
324 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
325 #define READ_SIZE 160
326
327 #define MASK_AVAIL              (1 << 0)        /*!< Channel available for PRI use */
328 #define MASK_INUSE              (1 << 1)        /*!< Channel currently in use */
329
330 #define CALLWAITING_SILENT_SAMPLES      ( (300 * 8) / READ_SIZE) /*!< 300 ms */
331 #define CALLWAITING_REPEAT_SAMPLES      ( (10000 * 8) / READ_SIZE) /*!< 10,000 ms */
332 #define CIDCW_EXPIRE_SAMPLES            ( (500 * 8) / READ_SIZE) /*!< 500 ms */
333 #define MIN_MS_SINCE_FLASH                      ( (2000) )      /*!< 2000 ms */
334 #define DEFAULT_RINGT                           ( (8000 * 8) / READ_SIZE) /*!< 8,000 ms */
335
336 struct dahdi_pvt;
337
338 static int ringt_base = DEFAULT_RINGT;
339
340 #ifdef HAVE_SS7
341
342 #define LINKSTATE_INALARM       (1 << 0)
343 #define LINKSTATE_STARTING      (1 << 1)
344 #define LINKSTATE_UP            (1 << 2)
345 #define LINKSTATE_DOWN          (1 << 3)
346
347 #define SS7_NAI_DYNAMIC         -1
348
349 struct dahdi_ss7 {
350         pthread_t master;                                               /*!< Thread of master */
351         ast_mutex_t lock;
352         int fds[NUM_DCHANS];
353         int numsigchans;
354         int linkstate[NUM_DCHANS];
355         int numchans;
356         int type;
357         enum {
358                 LINKSET_STATE_DOWN = 0,
359                 LINKSET_STATE_UP
360         } state;
361         char called_nai;                                                /*!< Called Nature of Address Indicator */
362         char calling_nai;                                               /*!< Calling Nature of Address Indicator */
363         char internationalprefix[10];                                   /*!< country access code ('00' for european dialplans) */
364         char nationalprefix[10];                                        /*!< area access code ('0' for european dialplans) */
365         char subscriberprefix[20];                                      /*!< area access code + area code ('0'+area code for european dialplans) */
366         char unknownprefix[20];                                         /*!< for unknown dialplans */
367         struct ss7 *ss7;
368         struct dahdi_pvt *pvts[MAX_CHANNELS];                           /*!< Member channel pvt structs */
369 };
370
371 static struct dahdi_ss7 linksets[NUM_SPANS];
372
373 static int cur_ss7type = -1;
374 static int cur_linkset = -1;
375 static int cur_pointcode = -1;
376 static int cur_cicbeginswith = -1;
377 static int cur_adjpointcode = -1;
378 static int cur_networkindicator = -1;
379 static int cur_defaultdpc = -1;
380 #endif /* HAVE_SS7 */
381
382 #ifdef HAVE_PRI
383
384 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
385 #define PRI_CHANNEL(p) ((p) & 0xff)
386 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
387 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
388
389 struct dahdi_pri {
390         pthread_t master;                                               /*!< Thread of master */
391         ast_mutex_t lock;                                               /*!< Mutex */
392         char idleext[AST_MAX_EXTENSION];                                /*!< Where to idle extra calls */
393         char idlecontext[AST_MAX_CONTEXT];                              /*!< What context to use for idle */
394         char idledial[AST_MAX_EXTENSION];                               /*!< What to dial before dumping */
395         int minunused;                                                  /*!< Min # of channels to keep empty */
396         int minidle;                                                    /*!< Min # of "idling" calls to keep active */
397         int nodetype;                                                   /*!< Node type */
398         int switchtype;                                                 /*!< Type of switch to emulate */
399         int nsf;                                                        /*!< Network-Specific Facilities */
400         int dialplan;                                                   /*!< Dialing plan */
401         int localdialplan;                                              /*!< Local dialing plan */
402         char internationalprefix[10];                                   /*!< country access code ('00' for european dialplans) */
403         char nationalprefix[10];                                        /*!< area access code ('0' for european dialplans) */
404         char localprefix[20];                                           /*!< area access code + area code ('0'+area code for european dialplans) */
405         char privateprefix[20];                                         /*!< for private dialplans */
406         char unknownprefix[20];                                         /*!< for unknown dialplans */
407         int dchannels[NUM_DCHANS];                                      /*!< What channel are the dchannels on */
408         int trunkgroup;                                                 /*!< What our trunkgroup is */
409         int mastertrunkgroup;                                           /*!< What trunk group is our master */
410         int prilogicalspan;                                             /*!< Logical span number within trunk group */
411         int numchans;                                                   /*!< Num of channels we represent */
412         int overlapdial;                                                /*!< In overlap dialing mode */
413         int facilityenable;                                             /*!< Enable facility IEs */
414         struct pri *dchans[NUM_DCHANS];                                 /*!< Actual d-channels */
415         int dchanavail[NUM_DCHANS];                                     /*!< Whether each channel is available */
416         struct pri *pri;                                                /*!< Currently active D-channel */
417         int debug;
418         int fds[NUM_DCHANS];                                            /*!< FD's for d-channels */
419         int offset;
420         int span;
421         int resetting;
422         int resetpos;
423         time_t lastreset;                                               /*!< time when unused channels were last reset */
424         long resetinterval;                                             /*!< Interval (in seconds) for resetting unused channels */
425         int sig;
426         struct dahdi_pvt *pvts[MAX_CHANNELS];                           /*!< Member channel pvt structs */
427         struct dahdi_pvt *crvs;                                         /*!< Member CRV structs */
428         struct dahdi_pvt *crvend;                                               /*!< Pointer to end of CRV structs */
429 };
430
431
432 static struct dahdi_pri pris[NUM_SPANS];
433
434 #if 0
435 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
436 #else
437 #define DEFAULT_PRI_DEBUG 0
438 #endif
439
440 static inline void pri_rel(struct dahdi_pri *pri)
441 {
442         ast_mutex_unlock(&pri->lock);
443 }
444
445 #else
446 /*! Shut up the compiler */
447 struct dahdi_pri;
448 #endif
449
450 #define SUB_REAL        0                       /*!< Active call */
451 #define SUB_CALLWAIT    1                       /*!< Call-Waiting call on hold */
452 #define SUB_THREEWAY    2                       /*!< Three-way call */
453
454 /* Polarity states */
455 #define POLARITY_IDLE   0
456 #define POLARITY_REV    1
457
458
459 struct distRingData {
460         int ring[3];
461         int range;
462 };
463 struct ringContextData {
464         char contextData[AST_MAX_CONTEXT];
465 };
466 struct dahdi_distRings {
467         struct distRingData ringnum[3];
468         struct ringContextData ringContext[3];
469 };
470
471 static char *subnames[] = {
472         "Real",
473         "Callwait",
474         "Threeway"
475 };
476
477 struct dahdi_subchannel {
478         int zfd;
479         struct ast_channel *owner;
480         int chan;
481         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
482         struct ast_frame f;             /*!< One frame for each channel.  How did this ever work before? */
483         unsigned int needringing:1;
484         unsigned int needbusy:1;
485         unsigned int needcongestion:1;
486         unsigned int needcallerid:1;
487         unsigned int needanswer:1;
488         unsigned int needflash:1;
489         unsigned int needhold:1;
490         unsigned int needunhold:1;
491         unsigned int linear:1;
492         unsigned int inthreeway:1;
493         DAHDI_CONFINFO curconf;
494 };
495
496 #define CONF_USER_REAL          (1 << 0)
497 #define CONF_USER_THIRDCALL     (1 << 1)
498
499 #define MAX_SLAVES      4
500
501 static struct dahdi_pvt {
502         ast_mutex_t lock;
503         struct ast_channel *owner;                      /*!< Our current active owner (if applicable) */
504                                                         /*!< Up to three channels can be associated with this call */
505                 
506         struct dahdi_subchannel sub_unused;             /*!< Just a safety precaution */
507         struct dahdi_subchannel subs[3];                        /*!< Sub-channels */
508         struct dahdi_confinfo saveconf;                 /*!< Saved conference info */
509
510         struct dahdi_pvt *slaves[MAX_SLAVES];           /*!< Slave to us (follows our conferencing) */
511         struct dahdi_pvt *master;                               /*!< Master to us (we follow their conferencing) */
512         int inconference;                               /*!< If our real should be in the conference */
513         
514         int sig;                                        /*!< Signalling style */
515         int radio;                                      /*!< radio type */
516         int outsigmod;                                  /*!< Outbound Signalling style (modifier) */
517         int oprmode;                                    /*!< "Operator Services" mode */
518         struct dahdi_pvt *oprpeer;                              /*!< "Operator Services" peer tech_pvt ptr */
519         float cid_rxgain;                                       /*!< "Gain to apply during caller id */
520         float rxgain;
521         float txgain;
522         int tonezone;                                   /*!< tone zone for this chan, or -1 for default */
523         struct dahdi_pvt *next;                         /*!< Next channel in list */
524         struct dahdi_pvt *prev;                         /*!< Prev channel in list */
525
526         /* flags */
527         unsigned int adsi:1;
528         unsigned int answeronpolarityswitch:1;
529         unsigned int busydetect:1;
530         unsigned int callreturn:1;
531         unsigned int callwaiting:1;
532         unsigned int callwaitingcallerid:1;
533         unsigned int cancallforward:1;
534         unsigned int canpark:1;
535         unsigned int confirmanswer:1;                   /*!< Wait for '#' to confirm answer */
536         unsigned int destroy:1;
537         unsigned int didtdd:1;                          /*!< flag to say its done it once */
538         unsigned int dialednone:1;
539         unsigned int dialing:1;
540         unsigned int digital:1;
541         unsigned int dnd:1;
542         unsigned int echobreak:1;
543         unsigned int echocanbridged:1;
544         unsigned int echocanon:1;
545         unsigned int faxhandled:1;                      /*!< Has a fax tone already been handled? */
546         unsigned int firstradio:1;
547         unsigned int hanguponpolarityswitch:1;
548         unsigned int hardwaredtmf:1;
549         unsigned int hidecallerid:1;
550         unsigned int hidecalleridname:1;      /*!< Hide just the name not the number for legacy PBX use */
551         unsigned int ignoredtmf:1;
552         unsigned int immediate:1;                       /*!< Answer before getting digits? */
553         unsigned int inalarm:1;
554         unsigned int mate:1;                            /*!< flag to say its in MATE mode */
555         unsigned int outgoing:1;
556         /* unsigned int overlapdial:1;                  unused and potentially confusing */
557         unsigned int permcallwaiting:1;
558         unsigned int permhidecallerid:1;                /*!< Whether to hide our outgoing caller ID or not */
559         unsigned int priindication_oob:1;
560         unsigned int priexclusive:1;
561         unsigned int pulse:1;
562         unsigned int pulsedial:1;                       /*!< whether a pulse dial phone is detected */
563         unsigned int restrictcid:1;                     /*!< Whether restrict the callerid -> only send ANI */
564         unsigned int threewaycalling:1;
565         unsigned int transfer:1;
566         unsigned int use_callerid:1;                    /*!< Whether or not to use caller id on this channel */
567         unsigned int use_callingpres:1;                 /*!< Whether to use the callingpres the calling switch sends */
568         unsigned int usedistinctiveringdetection:1;
569         unsigned int dahditrcallerid:1;                 /*!< should we use the callerid from incoming call on dahdi transfer or not */
570         unsigned int transfertobusy:1;                  /*!< allow flash-transfers to busy channels */
571         unsigned int mwimonitor_neon:1;                 /*!< monitor this FXO port for neon type MWI indication from other end */
572         unsigned int mwimonitor_fsk:1;                  /*!< monitor this FXO port for fsk MWI indication from other end */
573         unsigned int mwimonitoractive:1;                /*!< an MWI monitor thread is currently active */
574         /* Channel state or unavilability flags */
575         unsigned int inservice:1;
576         unsigned int locallyblocked:1;
577         unsigned int remotelyblocked:1;
578 #if defined(HAVE_PRI) || defined(HAVE_SS7)
579         unsigned int rlt:1;     
580         unsigned int alerting:1;
581         unsigned int alreadyhungup:1;
582         unsigned int isidlecall:1;
583         unsigned int proceeding:1;
584         unsigned int progress:1;
585         unsigned int resetting:1;
586         unsigned int setup_ack:1;
587 #endif
588         unsigned int use_smdi:1;                /* Whether to use SMDI on this channel */
589         struct ast_smdi_interface *smdi_iface;  /* The serial port to listen for SMDI data on */
590
591         struct dahdi_distRings drings;
592
593         char context[AST_MAX_CONTEXT];
594         char defcontext[AST_MAX_CONTEXT];
595         char exten[AST_MAX_EXTENSION];
596         char language[MAX_LANGUAGE];
597         char mohinterpret[MAX_MUSICCLASS];
598         char mohsuggest[MAX_MUSICCLASS];
599         char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
600 #if defined(PRI_ANI) || defined(HAVE_SS7)
601         char cid_ani[AST_MAX_EXTENSION];
602 #endif
603         int cid_ani2;
604         char cid_num[AST_MAX_EXTENSION];
605         int cid_ton;                                    /*!< Type Of Number (TON) */
606         char cid_name[AST_MAX_EXTENSION];
607         char lastcid_num[AST_MAX_EXTENSION];
608         char lastcid_name[AST_MAX_EXTENSION];
609         char *origcid_num;                              /*!< malloced original callerid */
610         char *origcid_name;                             /*!< malloced original callerid */
611         char callwait_num[AST_MAX_EXTENSION];
612         char callwait_name[AST_MAX_EXTENSION];
613         char rdnis[AST_MAX_EXTENSION];
614         char dnid[AST_MAX_EXTENSION];
615         ast_group_t group;
616         int law;
617         int confno;                                     /*!< Our conference */
618         int confusers;                                  /*!< Who is using our conference */
619         int propconfno;                                 /*!< Propagated conference number */
620         ast_group_t callgroup;
621         ast_group_t pickupgroup;
622         struct ast_variable *vars;
623         int channel;                                    /*!< Channel Number or CRV */
624         int span;                                       /*!< Span number */
625         time_t guardtime;                               /*!< Must wait this much time before using for new call */
626         int cid_signalling;                             /*!< CID signalling type bell202 or v23 */
627         int cid_start;                                  /*!< CID start indicator, polarity or ring */
628         int callingpres;                                /*!< The value of callling presentation that we're going to use when placing a PRI call */
629         int callwaitingrepeat;                          /*!< How many samples to wait before repeating call waiting */
630         int cidcwexpire;                                /*!< When to expire our muting for CID/CW */
631         unsigned char *cidspill;
632         int cidpos;
633         int cidlen;
634         int ringt;
635         int ringt_base;
636         int stripmsd;
637         int callwaitcas;
638         int callwaitrings;
639         struct {
640                 struct dahdi_echocanparams head;
641                 struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
642         } echocancel;
643         int echotraining;
644         char echorest[20];
645         int busycount;
646         int busy_tonelength;
647         int busy_quietlength;
648         int callprogress;
649         struct timeval flashtime;                       /*!< Last flash-hook time */
650         struct ast_dsp *dsp;
651         int cref;                                       /*!< Call reference number */
652         DAHDI_DIAL_OPERATION dop;
653         int whichwink;                                  /*!< SIG_FEATDMF_TA Which wink are we on? */
654         char finaldial[64];
655         char accountcode[AST_MAX_ACCOUNT_CODE];         /*!< Account code */
656         int amaflags;                                   /*!< AMA Flags */
657         struct tdd_state *tdd;                          /*!< TDD flag */
658         char call_forward[AST_MAX_EXTENSION];
659         char mailbox[AST_MAX_EXTENSION];
660         struct ast_event_sub *mwi_event_sub;
661         char dialdest[256];
662         int onhooktime;
663         int msgstate;
664         int distinctivering;                            /*!< Which distinctivering to use */
665         int cidrings;                                   /*!< Which ring to deliver CID on */
666         int dtmfrelax;                                  /*!< whether to run in relaxed DTMF mode */
667         int fake_event;
668         int polarityonanswerdelay;
669         struct timeval polaritydelaytv;
670         int sendcalleridafter;
671 #ifdef HAVE_PRI
672         struct dahdi_pri *pri;
673         struct dahdi_pvt *bearer;
674         struct dahdi_pvt *realcall;
675         q931_call *call;
676         int prioffset;
677         int logicalspan;
678 #endif  
679         int polarity;
680         int dsp_features;
681 #ifdef HAVE_SS7
682         struct dahdi_ss7 *ss7;
683         struct isup_call *ss7call;
684         char charge_number[50];
685         char gen_add_number[50];
686         char gen_dig_number[50];
687         char orig_called_num[50];
688         char redirecting_num[50];
689         char generic_name[50];
690         unsigned char gen_add_num_plan;
691         unsigned char gen_add_nai;
692         unsigned char gen_add_pres_ind;
693         unsigned char gen_add_type;
694         unsigned char gen_dig_type;
695         unsigned char gen_dig_scheme;
696         char jip_number[50];
697         unsigned char lspi_type;
698         unsigned char lspi_scheme;
699         unsigned char lspi_context;
700         char lspi_ident[50];
701         unsigned int call_ref_ident;
702         unsigned int call_ref_pc;
703         unsigned char calling_party_cat;
704         int transcap;
705         int cic;                                                        /*!< CIC associated with channel */
706         unsigned int dpc;                                               /*!< CIC's DPC */
707         unsigned int loopedback:1;
708 #endif
709         char begindigit;
710         int muting;
711 } *iflist = NULL, *ifend = NULL;
712
713 /*! \brief Channel configuration from chan_dahdi.conf .
714  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
715  * Generally there is a field here for every possible configuration item.
716  *
717  * The state of fields is saved along the parsing and whenever a 'channel'
718  * statement is reached, the current dahdi_chan_conf is used to configure the 
719  * channel (struct dahdi_pvt)
720  *
721  * \see dahdi_chan_init for the default values.
722  */
723 struct dahdi_chan_conf {
724         struct dahdi_pvt chan;
725 #ifdef HAVE_PRI
726         struct dahdi_pri pri;
727 #endif
728
729 #ifdef HAVE_SS7
730         struct dahdi_ss7 ss7;
731 #endif
732         DAHDI_PARAMS timing;
733         int is_sig_auto; /*!< Use channel signalling from DAHDI? */
734
735         char smdi_port[SMDI_MAX_FILENAME_LEN];
736 };
737
738 /*! returns a new dahdi_chan_conf with default values (by-value) */
739 static struct dahdi_chan_conf dahdi_chan_conf_default(void) {
740         /* recall that if a field is not included here it is initialized
741          * to 0 or equivalent
742          */
743         struct dahdi_chan_conf conf = {
744 #ifdef HAVE_PRI
745                 .pri = {
746                         .nsf = PRI_NSF_NONE,
747                         .switchtype = PRI_SWITCH_NI2,
748                         .dialplan = PRI_UNKNOWN + 1,
749                         .localdialplan = PRI_NATIONAL_ISDN + 1,
750                         .nodetype = PRI_CPE,
751
752                         .minunused = 2,
753                         .idleext = "",
754                         .idledial = "",
755                         .internationalprefix = "",
756                         .nationalprefix = "",
757                         .localprefix = "",
758                         .privateprefix = "",
759                         .unknownprefix = "",
760                         .resetinterval = -1,
761                 },
762 #endif
763 #ifdef HAVE_SS7
764                 .ss7 = {
765                         .called_nai = SS7_NAI_NATIONAL,
766                         .calling_nai = SS7_NAI_NATIONAL,
767                         .internationalprefix = "",
768                         .nationalprefix = "",
769                         .subscriberprefix = "",
770                         .unknownprefix = ""
771                 },
772 #endif
773                 .chan = {
774                         .context = "default",
775                         .cid_num = "",
776                         .cid_name = "",
777                         .mohinterpret = "default",
778                         .mohsuggest = "",
779                         .parkinglot = "",
780                         .transfertobusy = 1,
781
782                         .cid_signalling = CID_SIG_BELL,
783                         .cid_start = CID_START_RING,
784                         .dahditrcallerid = 0,
785                         .use_callerid = 1,
786                         .sig = -1,
787                         .outsigmod = -1,
788
789                         .cid_rxgain = +5.0,
790
791                         .tonezone = -1,
792
793                         .echocancel.head.tap_length = 1,
794
795                         .busycount = 3,
796
797                         .accountcode = "",
798
799                         .mailbox = "",
800
801
802                         .polarityonanswerdelay = 600,
803
804                         .sendcalleridafter = DEFAULT_CIDRINGS
805                 },
806                 .timing = {
807                         .prewinktime = -1,
808                         .preflashtime = -1,
809                         .winktime = -1,
810                         .flashtime = -1,
811                         .starttime = -1,
812                         .rxwinktime = -1,
813                         .rxflashtime = -1,
814                         .debouncetime = -1
815                 },
816                 .is_sig_auto = 1,
817                 .smdi_port = "/dev/ttyS0",
818         };
819
820         return conf;
821 }
822
823
824 static struct ast_channel *dahdi_request(const char *type, int format, void *data, int *cause);
825 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
826 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
827 static int dahdi_sendtext(struct ast_channel *c, const char *text);
828 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
829 static int dahdi_hangup(struct ast_channel *ast);
830 static int dahdi_answer(struct ast_channel *ast);
831 static struct ast_frame *dahdi_read(struct ast_channel *ast);
832 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
833 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
834 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
835 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
836 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
837 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
838
839 static const struct ast_channel_tech dahdi_tech = {
840         .type = "DAHDI",
841         .description = tdesc,
842         .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
843         .requester = dahdi_request,
844         .send_digit_begin = dahdi_digit_begin,
845         .send_digit_end = dahdi_digit_end,
846         .send_text = dahdi_sendtext,
847         .call = dahdi_call,
848         .hangup = dahdi_hangup,
849         .answer = dahdi_answer,
850         .read = dahdi_read,
851         .write = dahdi_write,
852         .bridge = dahdi_bridge,
853         .exception = dahdi_exception,
854         .indicate = dahdi_indicate,
855         .fixup = dahdi_fixup,
856         .setoption = dahdi_setoption,
857         .func_channel_read = dahdi_func_read,
858 };
859
860 #ifdef HAVE_PRI
861 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
862 #else
863 #define GET_CHANNEL(p) ((p)->channel)
864 #endif
865
866 struct dahdi_pvt *round_robin[32];
867
868 #ifdef HAVE_PRI
869 static inline int pri_grab(struct dahdi_pvt *pvt, struct dahdi_pri *pri)
870 {
871         int res;
872         /* Grab the lock first */
873         do {
874                 res = ast_mutex_trylock(&pri->lock);
875                 if (res) {
876                         DEADLOCK_AVOIDANCE(&pvt->lock);
877                 }
878         } while (res);
879         /* Then break the poll */
880         pthread_kill(pri->master, SIGURG);
881         return 0;
882 }
883 #endif
884
885 #ifdef HAVE_SS7
886 static inline void ss7_rel(struct dahdi_ss7 *ss7)
887 {
888         ast_mutex_unlock(&ss7->lock);
889 }
890
891 static inline int ss7_grab(struct dahdi_pvt *pvt, struct dahdi_ss7 *pri)
892 {
893         int res;
894         /* Grab the lock first */
895         do {
896                 res = ast_mutex_trylock(&pri->lock);
897                 if (res) {
898                         ast_mutex_unlock(&pvt->lock);
899                         /* Release the lock and try again */
900                         usleep(1);
901                         ast_mutex_lock(&pvt->lock);
902                 }
903         } while (res);
904         /* Then break the poll */
905         pthread_kill(pri->master, SIGURG);
906         return 0;
907 }
908 #endif
909 #define NUM_CADENCE_MAX 25
910 static int num_cadence = 4;
911 static int user_has_defined_cadences = 0;
912
913 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
914         { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
915         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
916         { { 125, 125, 125, 125, 125, 4000 } },  /*!< Three short bursts */
917         { { 1000, 500, 2500, 5000 } },  /*!< Long ring */
918 };
919
920 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
921  * is 1, the second pause is 2 and so on.
922  */
923
924 static int cidrings[NUM_CADENCE_MAX] = {
925         2,                                                                              /*!< Right after first long ring */
926         4,                                                                              /*!< Right after long part */
927         3,                                                                              /*!< After third chirp */
928         2,                                                                              /*!< Second spell */
929 };
930
931 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
932                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
933
934 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
935 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
936
937 static int dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok)
938 {
939         int res;
940         if (p->subs[0].owner == ast)
941                 res = 0;
942         else if (p->subs[1].owner == ast)
943                 res = 1;
944         else if (p->subs[2].owner == ast)
945                 res = 2;
946         else {
947                 res = -1;
948                 if (!nullok)
949                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
950         }
951         return res;
952 }
953
954 #ifdef HAVE_PRI
955 static void wakeup_sub(struct dahdi_pvt *p, int a, struct dahdi_pri *pri)
956 #else
957 static void wakeup_sub(struct dahdi_pvt *p, int a, void *pri)
958 #endif
959 {
960 #ifdef HAVE_PRI
961         if (pri)
962                 ast_mutex_unlock(&pri->lock);
963 #endif                  
964         for (;;) {
965                 if (p->subs[a].owner) {
966                         if (ast_channel_trylock(p->subs[a].owner)) {
967                                 DEADLOCK_AVOIDANCE(&p->lock);
968                         } else {
969                                 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
970                                 ast_channel_unlock(p->subs[a].owner);
971                                 break;
972                         }
973                 } else
974                         break;
975         }
976 #ifdef HAVE_PRI
977         if (pri)
978                 ast_mutex_lock(&pri->lock);
979 #endif                  
980 }
981
982 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f, void *data)
983 {
984 #ifdef HAVE_PRI
985         struct dahdi_pri *pri = (struct dahdi_pri*) data;
986 #endif
987 #ifdef HAVE_SS7
988         struct dahdi_ss7 *ss7 = (struct dahdi_ss7*) data;
989 #endif
990         /* We must unlock the PRI to avoid the possibility of a deadlock */
991 #if defined(HAVE_PRI) || defined(HAVE_SS7)
992         if (data) {
993                 switch (p->sig) {
994 #ifdef HAVE_PRI
995                 case SIG_BRI:
996                 case SIG_BRI_PTMP:
997                 case SIG_PRI:
998                         ast_mutex_unlock(&pri->lock);
999                         break;
1000 #endif
1001 #ifdef HAVE_SS7
1002                 case SIG_SS7:
1003                         ast_mutex_unlock(&ss7->lock);
1004                         break;
1005 #endif
1006                 default:
1007                         break;
1008                 }
1009         }
1010 #endif          
1011         for (;;) {
1012                 if (p->owner) {
1013                         if (ast_channel_trylock(p->owner)) {
1014                                 DEADLOCK_AVOIDANCE(&p->lock);
1015                         } else {
1016                                 ast_queue_frame(p->owner, f);
1017                                 ast_channel_unlock(p->owner);
1018                                 break;
1019                         }
1020                 } else
1021                         break;
1022         }
1023 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1024         if (data) {
1025                 switch (p->sig) {
1026 #ifdef HAVE_PRI
1027                 case SIG_BRI:
1028                 case SIG_BRI_PTMP:
1029                 case SIG_PRI:
1030                         ast_mutex_lock(&pri->lock);
1031                         break;
1032 #endif
1033 #ifdef HAVE_SS7
1034                 case SIG_SS7:
1035                         ast_mutex_lock(&ss7->lock);
1036                         break;
1037 #endif
1038                 default:
1039                         break;
1040                 }
1041         }
1042
1043 #endif          
1044 }
1045
1046 static int restore_gains(struct dahdi_pvt *p);
1047
1048 static void swap_subs(struct dahdi_pvt *p, int a, int b)
1049 {
1050         int tchan;
1051         int tinthreeway;
1052         struct ast_channel *towner;
1053
1054         ast_debug(1, "Swapping %d and %d\n", a, b);
1055
1056         tchan = p->subs[a].chan;
1057         towner = p->subs[a].owner;
1058         tinthreeway = p->subs[a].inthreeway;
1059
1060         p->subs[a].chan = p->subs[b].chan;
1061         p->subs[a].owner = p->subs[b].owner;
1062         p->subs[a].inthreeway = p->subs[b].inthreeway;
1063
1064         p->subs[b].chan = tchan;
1065         p->subs[b].owner = towner;
1066         p->subs[b].inthreeway = tinthreeway;
1067
1068         if (p->subs[a].owner) 
1069                 ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].zfd);
1070         if (p->subs[b].owner) 
1071                 ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].zfd);
1072         wakeup_sub(p, a, NULL);
1073         wakeup_sub(p, b, NULL);
1074 }
1075
1076 static int dahdi_open(char *fn)
1077 {
1078         int fd;
1079         int isnum;
1080         int chan = 0;
1081         int bs;
1082         int x;
1083         isnum = 1;
1084         for (x = 0; x < strlen(fn); x++) {
1085                 if (!isdigit(fn[x])) {
1086                         isnum = 0;
1087                         break;
1088                 }
1089         }
1090         if (isnum) {
1091                 chan = atoi(fn);
1092                 if (chan < 1) {
1093                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
1094                         return -1;
1095                 }
1096                 fn = "/dev/dahdi/channel";
1097         }
1098         fd = open(fn, O_RDWR | O_NONBLOCK);
1099         if (fd < 0) {
1100                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
1101                 return -1;
1102         }
1103         if (chan) {
1104                 if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
1105                         x = errno;
1106                         close(fd);
1107                         errno = x;
1108                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
1109                         return -1;
1110                 }
1111         }
1112         bs = READ_SIZE;
1113         if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
1114                 ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
1115                 x = errno;
1116                 close(fd);
1117                 errno = x;
1118                 return -1;
1119         }
1120         return fd;
1121 }
1122
1123 static void dahdi_close(int fd)
1124 {
1125         if (fd > 0)
1126                 close(fd);
1127 }
1128
1129 static int dahdi_setlinear(int zfd, int linear)
1130 {
1131         int res;
1132         res = ioctl(zfd, DAHDI_SETLINEAR, &linear);
1133         if (res)
1134                 return res;
1135         return 0;
1136 }
1137
1138
1139 static int alloc_sub(struct dahdi_pvt *p, int x)
1140 {
1141         DAHDI_BUFFERINFO bi;
1142         int res;
1143         if (p->subs[x].zfd >= 0) {
1144                 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
1145                 return -1;
1146         }
1147
1148         p->subs[x].zfd = dahdi_open("/dev/dahdi/pseudo");
1149         if (p->subs[x].zfd <= -1) {
1150                 ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
1151                 return -1;
1152         }
1153
1154         res = ioctl(p->subs[x].zfd, DAHDI_GET_BUFINFO, &bi);
1155         if (!res) {
1156                 bi.txbufpolicy = DAHDI_POLICY_IMMEDIATE;
1157                 bi.rxbufpolicy = DAHDI_POLICY_IMMEDIATE;
1158                 bi.numbufs = numbufs;
1159                 res = ioctl(p->subs[x].zfd, DAHDI_SET_BUFINFO, &bi);
1160                 if (res < 0) {
1161                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d\n", x);
1162                 }
1163         } else 
1164                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d\n", x);
1165
1166         if (ioctl(p->subs[x].zfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
1167                 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d\n", p->subs[x].zfd);
1168                 dahdi_close(p->subs[x].zfd);
1169                 p->subs[x].zfd = -1;
1170                 return -1;
1171         }
1172         ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].zfd, p->subs[x].chan);
1173         return 0;
1174 }
1175
1176 static int unalloc_sub(struct dahdi_pvt *p, int x)
1177 {
1178         if (!x) {
1179                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
1180                 return -1;
1181         }
1182         ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
1183         if (p->subs[x].zfd > -1) {
1184                 dahdi_close(p->subs[x].zfd);
1185         }
1186         p->subs[x].zfd = -1;
1187         p->subs[x].linear = 0;
1188         p->subs[x].chan = 0;
1189         p->subs[x].owner = NULL;
1190         p->subs[x].inthreeway = 0;
1191         p->polarity = POLARITY_IDLE;
1192         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
1193         return 0;
1194 }
1195
1196 static int digit_to_dtmfindex(char digit)
1197 {
1198         if (isdigit(digit))
1199                 return DAHDI_TONE_DTMF_BASE + (digit - '0');
1200         else if (digit >= 'A' && digit <= 'D')
1201                 return DAHDI_TONE_DTMF_A + (digit - 'A');
1202         else if (digit >= 'a' && digit <= 'd')
1203                 return DAHDI_TONE_DTMF_A + (digit - 'a');
1204         else if (digit == '*')
1205                 return DAHDI_TONE_DTMF_s;
1206         else if (digit == '#')
1207                 return DAHDI_TONE_DTMF_p;
1208         else
1209                 return -1;
1210 }
1211
1212 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
1213 {
1214         struct dahdi_pvt *pvt;
1215         int index;
1216         int dtmf = -1;
1217         
1218         pvt = chan->tech_pvt;
1219
1220         ast_mutex_lock(&pvt->lock);
1221
1222         index = dahdi_get_index(chan, pvt, 0);
1223
1224         if ((index != SUB_REAL) || !pvt->owner)
1225                 goto out;
1226
1227 #ifdef HAVE_PRI
1228         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP)) 
1229                         && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
1230                 if (pvt->setup_ack) {
1231                         if (!pri_grab(pvt, pvt->pri)) {
1232                                 pri_information(pvt->pri->pri, pvt->call, digit);
1233                                 pri_rel(pvt->pri);
1234                         } else
1235                                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
1236                 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
1237                         int res;
1238                         ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1239                         res = strlen(pvt->dialdest);
1240                         pvt->dialdest[res++] = digit;
1241                         pvt->dialdest[res] = '\0';
1242                 }
1243                 goto out;
1244         }
1245 #endif
1246         if ((dtmf = digit_to_dtmfindex(digit)) == -1)
1247                 goto out;
1248
1249         if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].zfd, DAHDI_SENDTONE, &dtmf)) {
1250                 int res;
1251                 DAHDI_DIAL_OPERATION zo = {
1252                         .op = DAHDI_DIAL_OP_APPEND,
1253                 };
1254
1255                 zo.dialstr[0] = 'T';
1256                 zo.dialstr[1] = digit;
1257                 zo.dialstr[2] = '\0';
1258                 if ((res = ioctl(pvt->subs[SUB_REAL].zfd, DAHDI_DIAL, &zo)))
1259                         ast_log(LOG_WARNING, "Couldn't dial digit %c\n", digit);
1260                 else
1261                         pvt->dialing = 1;
1262         } else {
1263                 ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
1264                 pvt->dialing = 1;
1265                 pvt->begindigit = digit;
1266         }
1267
1268 out:
1269         ast_mutex_unlock(&pvt->lock);
1270
1271         return 0;
1272 }
1273
1274 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1275 {
1276         struct dahdi_pvt *pvt;
1277         int res = 0;
1278         int index;
1279         int x;
1280         
1281         pvt = chan->tech_pvt;
1282
1283         ast_mutex_lock(&pvt->lock);
1284         
1285         index = dahdi_get_index(chan, pvt, 0);
1286
1287         if ((index != SUB_REAL) || !pvt->owner || pvt->pulse)
1288                 goto out;
1289
1290 #ifdef HAVE_PRI
1291         /* This means that the digit was already sent via PRI signalling */
1292         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
1293                         && !pvt->begindigit)
1294                 goto out;
1295 #endif
1296
1297         if (pvt->begindigit) {
1298                 x = -1;
1299                 ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
1300                 res = ioctl(pvt->subs[SUB_REAL].zfd, DAHDI_SENDTONE, &x);
1301                 pvt->dialing = 0;
1302                 pvt->begindigit = 0;
1303         }
1304
1305 out:
1306         ast_mutex_unlock(&pvt->lock);
1307
1308         return res;
1309 }
1310
1311 static char *events[] = {
1312         "No event",
1313         "On hook",
1314         "Ring/Answered",
1315         "Wink/Flash",
1316         "Alarm",
1317         "No more alarm",
1318         "HDLC Abort",
1319         "HDLC Overrun",
1320         "HDLC Bad FCS",
1321         "Dial Complete",
1322         "Ringer On",
1323         "Ringer Off",
1324         "Hook Transition Complete",
1325         "Bits Changed",
1326         "Pulse Start",
1327         "Timer Expired",
1328         "Timer Ping",
1329         "Polarity Reversal",
1330         "Ring Begin",
1331 };
1332
1333 static struct {
1334         int alarm;
1335         char *name;
1336 } alarms[] = {
1337         { DAHDI_ALARM_RED, "Red Alarm" },
1338         { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
1339         { DAHDI_ALARM_BLUE, "Blue Alarm" },
1340         { DAHDI_ALARM_RECOVER, "Recovering" },
1341         { DAHDI_ALARM_LOOPBACK, "Loopback" },
1342         { DAHDI_ALARM_NOTOPEN, "Not Open" },
1343         { DAHDI_ALARM_NONE, "None" },
1344 };
1345
1346 static char *alarm2str(int alarm)
1347 {
1348         int x;
1349         for (x = 0; x < sizeof(alarms) / sizeof(alarms[0]); x++) {
1350                 if (alarms[x].alarm & alarm)
1351                         return alarms[x].name;
1352         }
1353         return alarm ? "Unknown Alarm" : "No Alarm";
1354 }
1355
1356 static char *event2str(int event)
1357 {
1358         static char buf[256];
1359         if ((event < (sizeof(events) / sizeof(events[0]))) && (event > -1))
1360                 return events[event];
1361         sprintf(buf, "Event %d", event); /* safe */
1362         return buf;
1363 }
1364
1365 #ifdef HAVE_PRI
1366 static char *dialplan2str(int dialplan)
1367 {
1368         if (dialplan == -1 || dialplan == -2) {
1369                 return("Dynamically set dialplan in ISDN");
1370         }
1371         return (pri_plan2str(dialplan));
1372 }
1373 #endif
1374
1375 static char *dahdi_sig2str(int sig)
1376 {
1377         static char buf[256];
1378         switch (sig) {
1379         case SIG_EM:
1380                 return "E & M Immediate";
1381         case SIG_EMWINK:
1382                 return "E & M Wink";
1383         case SIG_EM_E1:
1384                 return "E & M E1";
1385         case SIG_FEATD:
1386                 return "Feature Group D (DTMF)";
1387         case SIG_FEATDMF:
1388                 return "Feature Group D (MF)";
1389         case SIG_FEATDMF_TA:
1390                 return "Feature Groud D (MF) Tandem Access";
1391         case SIG_FEATB:
1392                 return "Feature Group B (MF)";
1393         case SIG_E911:
1394                 return "E911 (MF)";
1395         case SIG_FGC_CAMA:
1396                 return "FGC/CAMA (Dialpulse)";
1397         case SIG_FGC_CAMAMF:
1398                 return "FGC/CAMA (MF)";
1399         case SIG_FXSLS:
1400                 return "FXS Loopstart";
1401         case SIG_FXSGS:
1402                 return "FXS Groundstart";
1403         case SIG_FXSKS:
1404                 return "FXS Kewlstart";
1405         case SIG_FXOLS:
1406                 return "FXO Loopstart";
1407         case SIG_FXOGS:
1408                 return "FXO Groundstart";
1409         case SIG_FXOKS:
1410                 return "FXO Kewlstart";
1411         case SIG_PRI:
1412                 return "ISDN PRI";
1413         case SIG_BRI:
1414                 return "ISDN BRI Point to Point";
1415         case SIG_BRI_PTMP:
1416                 return "ISDN BRI Point to MultiPoint";
1417         case SIG_SS7:
1418                 return "SS7";
1419         case SIG_SF:
1420                 return "SF (Tone) Immediate";
1421         case SIG_SFWINK:
1422                 return "SF (Tone) Wink";
1423         case SIG_SF_FEATD:
1424                 return "SF (Tone) with Feature Group D (DTMF)";
1425         case SIG_SF_FEATDMF:
1426                 return "SF (Tone) with Feature Group D (MF)";
1427         case SIG_SF_FEATB:
1428                 return "SF (Tone) with Feature Group B (MF)";
1429         case SIG_GR303FXOKS:
1430                 return "GR-303 with FXOKS";
1431         case SIG_GR303FXSKS:
1432                 return "GR-303 with FXSKS";
1433         case 0:
1434                 return "Pseudo";
1435         default:
1436                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1437                 return buf;
1438         }
1439 }
1440
1441 #define sig2str dahdi_sig2str
1442
1443 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index, int slavechannel)
1444 {
1445         /* If the conference already exists, and we're already in it
1446            don't bother doing anything */
1447         DAHDI_CONFINFO zi;
1448         
1449         memset(&zi, 0, sizeof(zi));
1450         zi.chan = 0;
1451
1452         if (slavechannel > 0) {
1453                 /* If we have only one slave, do a digital mon */
1454                 zi.confmode = DAHDI_CONF_DIGITALMON;
1455                 zi.confno = slavechannel;
1456         } else {
1457                 if (!index) {
1458                         /* Real-side and pseudo-side both participate in conference */
1459                         zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
1460                                 DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
1461                 } else
1462                         zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
1463                 zi.confno = p->confno;
1464         }
1465         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1466                 return 0;
1467         if (c->zfd < 0)
1468                 return 0;
1469         if (ioctl(c->zfd, DAHDI_SETCONF, &zi)) {
1470                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d\n", c->zfd, zi.confmode, zi.confno);
1471                 return -1;
1472         }
1473         if (slavechannel < 1) {
1474                 p->confno = zi.confno;
1475         }
1476         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1477         ast_debug(1, "Added %d to conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1478         return 0;
1479 }
1480
1481 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
1482 {
1483         /* If they're listening to our channel, they're ours */ 
1484         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
1485                 return 1;
1486         /* If they're a talker on our (allocated) conference, they're ours */
1487         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
1488                 return 1;
1489         return 0;
1490 }
1491
1492 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index)
1493 {
1494         DAHDI_CONFINFO zi;
1495         if (/* Can't delete if there's no zfd */
1496                 (c->zfd < 0) ||
1497                 /* Don't delete from the conference if it's not our conference */
1498                 !isourconf(p, c)
1499                 /* Don't delete if we don't think it's conferenced at all (implied) */
1500                 ) return 0;
1501         memset(&zi, 0, sizeof(zi));
1502         zi.chan = 0;
1503         zi.confno = 0;
1504         zi.confmode = 0;
1505         if (ioctl(c->zfd, DAHDI_SETCONF, &zi)) {
1506                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1507                 return -1;
1508         }
1509         ast_debug(1, "Removed %d from conference %d/%d\n", c->zfd, c->curconf.confmode, c->curconf.confno);
1510         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1511         return 0;
1512 }
1513
1514 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
1515 {
1516         int x;
1517         int useslavenative;
1518         struct dahdi_pvt *slave = NULL;
1519         /* Start out optimistic */
1520         useslavenative = 1;
1521         /* Update conference state in a stateless fashion */
1522         for (x = 0; x < 3; x++) {
1523                 /* Any three-way calling makes slave native mode *definitely* out
1524                    of the question */
1525                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway)
1526                         useslavenative = 0;
1527         }
1528         /* If we don't have any 3-way calls, check to see if we have
1529            precisely one slave */
1530         if (useslavenative) {
1531                 for (x = 0; x < MAX_SLAVES; x++) {
1532                         if (p->slaves[x]) {
1533                                 if (slave) {
1534                                         /* Whoops already have a slave!  No 
1535                                            slave native and stop right away */
1536                                         slave = NULL;
1537                                         useslavenative = 0;
1538                                         break;
1539                                 } else {
1540                                         /* We have one slave so far */
1541                                         slave = p->slaves[x];
1542                                 }
1543                         }
1544                 }
1545         }
1546         /* If no slave, slave native definitely out */
1547         if (!slave)
1548                 useslavenative = 0;
1549         else if (slave->law != p->law) {
1550                 useslavenative = 0;
1551                 slave = NULL;
1552         }
1553         if (out)
1554                 *out = slave;
1555         return useslavenative;
1556 }
1557
1558 static int reset_conf(struct dahdi_pvt *p)
1559 {
1560         DAHDI_CONFINFO zi;
1561         memset(&zi, 0, sizeof(zi));
1562         p->confno = -1;
1563         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1564         if (p->subs[SUB_REAL].zfd > -1) {
1565                 if (ioctl(p->subs[SUB_REAL].zfd, DAHDI_SETCONF, &zi))
1566                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d!\n", p->channel);
1567         }
1568         return 0;
1569 }
1570
1571 static int update_conf(struct dahdi_pvt *p)
1572 {
1573         int needconf = 0;
1574         int x;
1575         int useslavenative;
1576         struct dahdi_pvt *slave = NULL;
1577
1578         useslavenative = isslavenative(p, &slave);
1579         /* Start with the obvious, general stuff */
1580         for (x = 0; x < 3; x++) {
1581                 /* Look for three way calls */
1582                 if ((p->subs[x].zfd > -1) && p->subs[x].inthreeway) {
1583                         conf_add(p, &p->subs[x], x, 0);
1584                         needconf++;
1585                 } else {
1586                         conf_del(p, &p->subs[x], x);
1587                 }
1588         }
1589         /* If we have a slave, add him to our conference now. or DAX
1590            if this is slave native */
1591         for (x = 0; x < MAX_SLAVES; x++) {
1592                 if (p->slaves[x]) {
1593                         if (useslavenative)
1594                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1595                         else {
1596                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1597                                 needconf++;
1598                         }
1599                 }
1600         }
1601         /* If we're supposed to be in there, do so now */
1602         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1603                 if (useslavenative)
1604                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1605                 else {
1606                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1607                         needconf++;
1608                 }
1609         }
1610         /* If we have a master, add ourselves to his conference */
1611         if (p->master) {
1612                 if (isslavenative(p->master, NULL)) {
1613                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1614                 } else {
1615                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1616                 }
1617         }
1618         if (!needconf) {
1619                 /* Nobody is left (or should be left) in our conference.
1620                    Kill it. */
1621                 p->confno = -1;
1622         }
1623         ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1624         return 0;
1625 }
1626
1627 static void dahdi_enable_ec(struct dahdi_pvt *p)
1628 {
1629         int x;
1630         int res;
1631         if (!p)
1632                 return;
1633         if (p->echocanon) {
1634                 ast_debug(1, "Echo cancellation already on\n");
1635                 return;
1636         }
1637         if (p->digital) {
1638                 ast_debug(1, "Echo cancellation isn't required on digital connection\n");
1639                 return;
1640         }
1641         if (p->echocancel.head.tap_length) {
1642                 if ((p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP) || (p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
1643                         x = 1;
1644                         res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_AUDIOMODE, &x);
1645                         if (res)
1646                                 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
1647                 }
1648                 res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
1649                 if (res)  {
1650                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
1651                 } else {
1652                         p->echocanon = 1;
1653                         ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
1654                 }
1655         } else
1656                 ast_debug(1, "No echo cancellation requested\n");
1657 }
1658
1659 static void dahdi_train_ec(struct dahdi_pvt *p)
1660 {
1661         int x;
1662         int res;
1663         
1664         if (p && p->echocanon && p->echotraining) {
1665                 x = p->echotraining;
1666                 res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_ECHOTRAIN, &x);
1667                 if (res)
1668                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d\n", p->channel);
1669                 else
1670                         ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
1671         } else {
1672                 ast_debug(1, "No echo training requested\n");
1673         }
1674 }
1675
1676 static void dahdi_disable_ec(struct dahdi_pvt *p)
1677 {
1678         int res;
1679
1680         if (p->echocanon) {
1681                 struct dahdi_echocanparams ecp = { .tap_length = 0 };
1682
1683                 res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
1684
1685                 if (res)
1686                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d\n", p->channel);
1687                 else
1688                         ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
1689         }
1690
1691         p->echocanon = 0;
1692 }
1693
1694 static void fill_txgain(struct dahdi_gains *g, float gain, int law)
1695 {
1696         int j;
1697         int k;
1698         float linear_gain = pow(10.0, gain / 20.0);
1699
1700         switch (law) {
1701         case DAHDI_LAW_ALAW:
1702                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1703                         if (gain) {
1704                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1705                                 if (k > 32767) k = 32767;
1706                                 if (k < -32767) k = -32767;
1707                                 g->txgain[j] = AST_LIN2A(k);
1708                         } else {
1709                                 g->txgain[j] = j;
1710                         }
1711                 }
1712                 break;
1713         case DAHDI_LAW_MULAW:
1714                 for (j = 0; j < (sizeof(g->txgain) / sizeof(g->txgain[0])); j++) {
1715                         if (gain) {
1716                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1717                                 if (k > 32767) k = 32767;
1718                                 if (k < -32767) k = -32767;
1719                                 g->txgain[j] = AST_LIN2MU(k);
1720                         } else {
1721                                 g->txgain[j] = j;
1722                         }
1723                 }
1724                 break;
1725         }
1726 }
1727
1728 static void fill_rxgain(struct dahdi_gains *g, float gain, int law)
1729 {
1730         int j;
1731         int k;
1732         float linear_gain = pow(10.0, gain / 20.0);
1733
1734         switch (law) {
1735         case DAHDI_LAW_ALAW:
1736                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1737                         if (gain) {
1738                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1739                                 if (k > 32767) k = 32767;
1740                                 if (k < -32767) k = -32767;
1741                                 g->rxgain[j] = AST_LIN2A(k);
1742                         } else {
1743                                 g->rxgain[j] = j;
1744                         }
1745                 }
1746                 break;
1747         case DAHDI_LAW_MULAW:
1748                 for (j = 0; j < (sizeof(g->rxgain) / sizeof(g->rxgain[0])); j++) {
1749                         if (gain) {
1750                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1751                                 if (k > 32767) k = 32767;
1752                                 if (k < -32767) k = -32767;
1753                                 g->rxgain[j] = AST_LIN2MU(k);
1754                         } else {
1755                                 g->rxgain[j] = j;
1756                         }
1757                 }
1758                 break;
1759         }
1760 }
1761
1762 static int set_actual_txgain(int fd, int chan, float gain, int law)
1763 {
1764         struct dahdi_gains g;
1765         int res;
1766
1767         memset(&g, 0, sizeof(g));
1768         g.chan = chan;
1769         res = ioctl(fd, DAHDI_GETGAINS, &g);
1770         if (res) {
1771                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
1772                 return res;
1773         }
1774
1775         fill_txgain(&g, gain, law);
1776
1777         return ioctl(fd, DAHDI_SETGAINS, &g);
1778 }
1779
1780 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1781 {
1782         struct dahdi_gains g;
1783         int res;
1784
1785         memset(&g, 0, sizeof(g));
1786         g.chan = chan;
1787         res = ioctl(fd, DAHDI_GETGAINS, &g);
1788         if (res) {
1789                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
1790                 return res;
1791         }
1792
1793         fill_rxgain(&g, gain, law);
1794
1795         return ioctl(fd, DAHDI_SETGAINS, &g);
1796 }
1797
1798 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1799 {
1800         return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1801 }
1802
1803 static int bump_gains(struct dahdi_pvt *p)
1804 {
1805         int res;
1806
1807         /* Bump receive gain by value stored in cid_rxgain */
1808         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain + p->cid_rxgain, p->txgain, p->law);
1809         if (res) {
1810                 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1811                 return -1;
1812         }
1813
1814         return 0;
1815 }
1816
1817 static int restore_gains(struct dahdi_pvt *p)
1818 {
1819         int res;
1820
1821         res = set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
1822         if (res) {
1823                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1824                 return -1;
1825         }
1826
1827         return 0;
1828 }
1829
1830 static inline int dahdi_set_hook(int fd, int hs)
1831 {
1832         int x, res;
1833
1834         x = hs;
1835         res = ioctl(fd, DAHDI_HOOK, &x);
1836
1837         if (res < 0) {
1838                 if (errno == EINPROGRESS)
1839                         return 0;
1840                 ast_log(LOG_WARNING, "DAHDI hook failed: %s\n", strerror(errno));
1841         }
1842
1843         return res;
1844 }
1845
1846 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
1847 {
1848         int x, y, res;
1849         x = muted;
1850         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
1851                 y = 1;
1852                 res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_AUDIOMODE, &y);
1853                 if (res)
1854                         ast_log(LOG_WARNING, "Unable to set audio mode on '%d'\n", p->channel);
1855         }
1856         res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_CONFMUTE, &x);
1857         if (res < 0)
1858                 ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1859         return res;
1860 }
1861
1862 static int save_conference(struct dahdi_pvt *p)
1863 {
1864         struct dahdi_confinfo c;
1865         int res;
1866         if (p->saveconf.confmode) {
1867                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1868                 return -1;
1869         }
1870         p->saveconf.chan = 0;
1871         res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_GETCONF, &p->saveconf);
1872         if (res) {
1873                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1874                 p->saveconf.confmode = 0;
1875                 return -1;
1876         }
1877         c.chan = 0;
1878         c.confno = 0;
1879         c.confmode = DAHDI_CONF_NORMAL;
1880         res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_SETCONF, &c);
1881         if (res) {
1882                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1883                 return -1;
1884         }
1885         ast_debug(1, "Disabled conferencing\n");
1886         return 0;
1887 }
1888
1889 /*!
1890  * \brief Send MWI state change
1891  *
1892  * \arg mailbox_full This is the mailbox associated with the FXO line that the
1893  *      MWI state has changed on.
1894  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
1895  *      whether there are messages waiting or not.
1896  *
1897  *  \return nothing
1898  *
1899  * This function does two things:
1900  *
1901  * 1) It generates an internal Asterisk event notifying any other module that
1902  *    cares about MWI that the state of a mailbox has changed.
1903  *
1904  * 2) It runs the script specified by the mwimonitornotify option to allow
1905  *    some custom handling of the state change.
1906  */
1907 static void notify_message(char *mailbox_full, int thereornot)
1908 {
1909         char s[sizeof(mwimonitornotify) + 80];
1910         struct ast_event *event;
1911         char *mailbox, *context;
1912
1913         /* Strip off @default */
1914         context = mailbox = ast_strdupa(mailbox_full);
1915         strsep(&context, "@");
1916         if (ast_strlen_zero(context))
1917                 context = "default";
1918
1919         if (!(event = ast_event_new(AST_EVENT_MWI,
1920                         AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
1921                         AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
1922                         AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
1923                         AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
1924                         AST_EVENT_IE_END))) {
1925                 return;
1926         }
1927
1928         ast_event_queue_and_cache(event,
1929                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR,
1930                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR,
1931                 AST_EVENT_IE_END);
1932
1933         if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
1934                 snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
1935                 ast_safe_system(s);
1936         }
1937 }
1938
1939 static int restore_conference(struct dahdi_pvt *p)
1940 {
1941         int res;
1942         if (p->saveconf.confmode) {
1943                 res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_SETCONF, &p->saveconf);
1944                 p->saveconf.confmode = 0;
1945                 if (res) {
1946                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
1947                         return -1;
1948                 }
1949         }
1950         ast_debug(1, "Restored conferencing\n");
1951         return 0;
1952 }
1953
1954 static int send_callerid(struct dahdi_pvt *p);
1955
1956 static int send_cwcidspill(struct dahdi_pvt *p)
1957 {
1958         p->callwaitcas = 0;
1959         p->cidcwexpire = 0;
1960         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
1961                 return -1;
1962         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
1963         /* Make sure we account for the end */
1964         p->cidlen += READ_SIZE * 4;
1965         p->cidpos = 0;
1966         send_callerid(p);
1967         ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
1968         return 0;
1969 }
1970
1971 static int has_voicemail(struct dahdi_pvt *p)
1972 {
1973         int new_msgs;
1974         struct ast_event *event;
1975         char *mailbox, *context;
1976
1977         mailbox = context = ast_strdupa(p->mailbox);
1978         strsep(&context, "@");
1979         if (ast_strlen_zero(context))
1980                 context = "default";
1981
1982         event = ast_event_get_cached(AST_EVENT_MWI,
1983                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
1984                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
1985                 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
1986                 AST_EVENT_IE_END);
1987
1988         if (event) {
1989                 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
1990                 ast_event_destroy(event);
1991         } else
1992                 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
1993
1994         return new_msgs;
1995 }
1996
1997 static int send_callerid(struct dahdi_pvt *p)
1998 {
1999         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
2000         int res;
2001         /* Take out of linear mode if necessary */
2002         if (p->subs[SUB_REAL].linear) {
2003                 p->subs[SUB_REAL].linear = 0;
2004                 dahdi_setlinear(p->subs[SUB_REAL].zfd, 0);
2005         }
2006         while (p->cidpos < p->cidlen) {
2007                 res = write(p->subs[SUB_REAL].zfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
2008                 if (res < 0) {
2009                         if (errno == EAGAIN)
2010                                 return 0;
2011                         else {
2012                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
2013                                 return -1;
2014                         }
2015                 }
2016                 if (!res)
2017                         return 0;
2018                 p->cidpos += res;
2019         }
2020         ast_free(p->cidspill);
2021         p->cidspill = NULL;
2022         if (p->callwaitcas) {
2023                 /* Wait for CID/CW to expire */
2024                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
2025         } else
2026                 restore_conference(p);
2027         return 0;
2028 }
2029
2030 static int dahdi_callwait(struct ast_channel *ast)
2031 {
2032         struct dahdi_pvt *p = ast->tech_pvt;
2033         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
2034         if (p->cidspill) {
2035                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
2036                 ast_free(p->cidspill);
2037         }
2038         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
2039                 return -1;
2040         save_conference(p);
2041         /* Silence */
2042         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
2043         if (!p->callwaitrings && p->callwaitingcallerid) {
2044                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
2045                 p->callwaitcas = 1;
2046                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
2047         } else {
2048                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
2049                 p->callwaitcas = 0;
2050                 p->cidlen = 2400 + READ_SIZE * 4;
2051         }
2052         p->cidpos = 0;
2053         send_callerid(p);
2054         
2055         return 0;
2056 }
2057
2058 #ifdef HAVE_SS7
2059 static unsigned char cid_pres2ss7pres(int cid_pres)
2060 {
2061          return (cid_pres >> 5) & 0x03;
2062 }
2063
2064 static unsigned char cid_pres2ss7screen(int cid_pres)
2065 {
2066         return cid_pres & 0x03;
2067 }
2068 #endif
2069
2070 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
2071 {
2072         struct dahdi_pvt *p = ast->tech_pvt;
2073         int x, res, index,mysig;
2074         char *c, *n, *l;
2075 #ifdef HAVE_PRI
2076         char *s = NULL;
2077 #endif
2078         char dest[256]; /* must be same length as p->dialdest */
2079         ast_mutex_lock(&p->lock);
2080         ast_copy_string(dest, rdest, sizeof(dest));
2081         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
2082         if ((ast->_state == AST_STATE_BUSY)) {
2083                 p->subs[SUB_REAL].needbusy = 1;
2084                 ast_mutex_unlock(&p->lock);
2085                 return 0;
2086         }
2087         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2088                 ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
2089                 ast_mutex_unlock(&p->lock);
2090                 return -1;
2091         }
2092         p->dialednone = 0;
2093         if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
2094         {
2095                 /* Special pseudo -- automatically up */
2096                 ast_setstate(ast, AST_STATE_UP); 
2097                 ast_mutex_unlock(&p->lock);
2098                 return 0;
2099         }
2100         x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
2101         res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_FLUSH, &x);
2102         if (res)
2103                 ast_log(LOG_WARNING, "Unable to flush input on channel %d\n", p->channel);
2104         p->outgoing = 1;
2105
2106         set_actual_gain(p->subs[SUB_REAL].zfd, 0, p->rxgain, p->txgain, p->law);
2107
2108         mysig = p->sig;
2109         if (p->outsigmod > -1)
2110                 mysig = p->outsigmod;
2111
2112         switch (mysig) {
2113         case SIG_FXOLS:
2114         case SIG_FXOGS:
2115         case SIG_FXOKS:
2116                 if (p->owner == ast) {
2117                         /* Normal ring, on hook */
2118                         
2119                         /* Don't send audio while on hook, until the call is answered */
2120                         p->dialing = 1;
2121                         if (p->use_callerid) {
2122                                 /* Generate the Caller-ID spill if desired */
2123                                 if (p->cidspill) {
2124                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
2125                                         ast_free(p->cidspill);
2126                                 }
2127                                 p->callwaitcas = 0;
2128                                 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
2129                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
2130                                         p->cidpos = 0;
2131                                         send_callerid(p);
2132                                 }
2133                         }
2134                         /* Choose proper cadence */
2135                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
2136                                 if (ioctl(p->subs[SUB_REAL].zfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
2137                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s'\n", p->distinctivering, ast->name);
2138                                 p->cidrings = cidrings[p->distinctivering - 1];
2139                         } else {
2140                                 if (ioctl(p->subs[SUB_REAL].zfd, DAHDI_SETCADENCE, NULL))
2141                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s'\n", ast->name);
2142                                 p->cidrings = p->sendcalleridafter;
2143                         }
2144
2145                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
2146                         c = strchr(dest, '/');
2147                         if (c)
2148                                 c++;
2149                         if (c && (strlen(c) < p->stripmsd)) {
2150                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2151                                 c = NULL;
2152                         }
2153                         if (c) {
2154                                 p->dop.op = DAHDI_DIAL_OP_REPLACE;
2155                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
2156                                 ast_debug(1, "FXO: setup deferred dialstring: %s\n", c);
2157                         } else {
2158                                 p->dop.dialstr[0] = '\0';
2159                         }
2160                         x = DAHDI_RING;
2161                         if (ioctl(p->subs[SUB_REAL].zfd, DAHDI_HOOK, &x) && (errno != EINPROGRESS)) {
2162                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
2163                                 ast_mutex_unlock(&p->lock);
2164                                 return -1;
2165                         }
2166                         p->dialing = 1;
2167                 } else {
2168                         /* Call waiting call */
2169                         p->callwaitrings = 0;
2170                         if (ast->cid.cid_num)
2171                                 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
2172                         else
2173                                 p->callwait_num[0] = '\0';
2174                         if (ast->cid.cid_name)
2175                                 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
2176                         else
2177                                 p->callwait_name[0] = '\0';
2178                         /* Call waiting tone instead */
2179                         if (dahdi_callwait(ast)) {
2180                                 ast_mutex_unlock(&p->lock);
2181                                 return -1;
2182                         }
2183                         /* Make ring-back */
2184                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].zfd, DAHDI_TONE_RINGTONE))
2185                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
2186                                 
2187                 }
2188                 n = ast->cid.cid_name;
2189                 l = ast->cid.cid_num;
2190                 if (l)
2191                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
2192                 else
2193                         p->lastcid_num[0] = '\0';
2194                 if (n)
2195                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
2196                 else
2197                         p->lastcid_name[0] = '\0';
2198                 ast_setstate(ast, AST_STATE_RINGING);
2199                 index = dahdi_get_index(ast, p, 0);
2200                 if (index > -1) {
2201                         p->subs[index].needringing = 1;
2202                 }
2203                 break;
2204         case SIG_FXSLS:
2205         case SIG_FXSGS:
2206         case SIG_FXSKS:
2207         case SIG_EMWINK:
2208         case SIG_EM:
2209         case SIG_EM_E1:
2210         case SIG_FEATD:
2211         case SIG_FEATDMF:
2212         case SIG_E911:
2213         case SIG_FGC_CAMA:
2214         case SIG_FGC_CAMAMF:
2215         case SIG_FEATB:
2216         case SIG_SFWINK:
2217         case SIG_SF:
2218         case SIG_SF_FEATD:
2219         case SIG_SF_FEATDMF:
2220         case SIG_FEATDMF_TA:
2221         case SIG_SF_FEATB:
2222                 c = strchr(dest, '/');
2223                 if (c)
2224                         c++;
2225                 else
2226                         c = "";
2227                 if (strlen(c) < p->stripmsd) {
2228                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2229                         ast_mutex_unlock(&p->lock);
2230                         return -1;
2231                 }
2232 #ifdef HAVE_PRI
2233                 /* Start the trunk, if not GR-303 */
2234                 if (!p->pri) {
2235 #endif
2236                         x = DAHDI_START;
2237                         res = ioctl(p->subs[SUB_REAL].zfd, DAHDI_HOOK, &x);
2238                         if (res < 0) {
2239                                 if (errno != EINPROGRESS) {
2240                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
2241                                         ast_mutex_unlock(&p->lock);
2242                                         return -1;
2243                                 }
2244                         }
2245 #ifdef HAVE_PRI
2246                 }
2247 #endif
2248                 ast_debug(1, "Dialing '%s'\n", c);
2249                 p->dop.op = DAHDI_DIAL_OP_REPLACE;
2250
2251                 c += p->stripmsd;
2252
2253                 switch (mysig) {
2254                 case SIG_FEATD:
2255                         l = ast->cid.cid_num;
2256                         if (l) 
2257                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
2258                         else
2259                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
2260                         break;
2261                 case SIG_FEATDMF:
2262                         l = ast->cid.cid_num;
2263                         if (l) 
2264                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
2265                         else
2266                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
2267                         break;
2268                 case SIG_FEATDMF_TA:
2269                 {
2270                         const char *cic, *ozz;
2271
2272                         /* If you have to go through a Tandem Access point you need to use this */
2273                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
2274                         if (!ozz)
2275                                 ozz = defaultozz;
2276                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
2277                         if (!cic)
2278                                 cic = defaultcic;
2279                         if (!ozz || !cic) {
2280                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
2281                                 ast_mutex_unlock(&p->lock);
2282                                 return -1;
2283                         }
2284                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
2285                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
2286                         p->whichwink = 0;
2287                 }
2288                         break;
2289                 case SIG_E911:
2290                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
2291                         break;
2292                 case SIG_FGC_CAMA:
2293                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
2294                         break;
2295                 case SIG_FGC_CAMAMF:
2296                 case SIG_FEATB:
2297                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
2298                         break;
2299                 default:
2300                         if (p->pulse)
2301                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
2302                         else
2303                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
2304                         break;
2305                 }
2306
2307                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
2308                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2309                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2310                         p->echorest[sizeof(p->echorest) - 1] = '\0';
2311                         p->echobreak = 1;
2312                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2313                 } else
2314                         p->echobreak = 0;
2315                 if (!res) {
2316                         if (ioctl(p->subs[SUB_REAL].zfd, DAHDI_DIAL, &p->dop)) {
2317                                 x = DAHDI_ONHOOK;
2318                                 ioctl(p->subs[SUB_REAL].zfd, DAHDI_HOOK, &x);
2319                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(errno));
2320                                 ast_mutex_unlock(&p->lock);
2321                                 return -1;
2322                         }
2323                 } else
2324                         ast_debug(1, "Deferring dialing...\n");
2325
2326                 p->dialing = 1;
2327                 if (ast_strlen_zero(c))
2328                         p->dialednone = 1;
2329                 ast_setstate(ast, AST_STATE_DIALING);
2330                 break;
2331         case 0:
2332                 /* Special pseudo -- automatically up*/
2333                 ast_setstate(ast, AST_STATE_UP);
2334                 break;          
2335         case SIG_PRI:
2336         case SIG_BRI:
2337         case SIG_BRI_PTMP:
2338         case SIG_SS7:
2339                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2340                 p->dialdest[0] = '\0';
2341                 break;
2342         default:
2343                 ast_debug(1, "not yet implemented\n");
2344                 ast_mutex_unlock(&p->lock);
2345                 return -1;
2346         }
2347 #ifdef HAVE_SS7
2348         if (p->ss7) {
2349                 char ss7_called_nai;
2350                 int called_nai_strip;
2351                 char ss7_calling_nai;
2352                 int calling_nai_strip;
2353                 const char *charge_str = NULL;
2354                 const char *gen_address = NULL;
2355                 const char *gen_digits = NULL;
2356                 const char *gen_dig_type = NULL;
2357                 const char *gen_dig_scheme = NULL;
2358                 const char *gen_name = NULL;
2359                 const char *jip_digits = NULL;
2360                 const char *lspi_ident = NULL;
2361                 const char *rlt_flag = NULL;
2362                 const char *call_ref_id = NULL;
2363                 const char *call_ref_pc = NULL;
2364                 const char *send_far = NULL;
2365
2366                 c = strchr(dest, '/');
2367                 if (c)
2368                         c++;
2369                 else
2370                         c = dest;
2371
2372                 if (!p->hidecallerid) {
2373                         l = ast->cid.cid_num;
2374                 } else {
2375                         l = NULL;
2376                 }
2377
2378                 if (ss7_grab(p, p->ss7)) {
2379                         ast_log(LOG_WARNING, "Failed to grab SS7!\n");
2380                         ast_mutex_unlock(&p->lock);
2381                         return -1;
2382                 }
2383                 p->digital = IS_DIGITAL(ast->transfercapability);
2384                 p->ss7call = isup_new_call(p->ss7->ss7);
2385
2386                 if (!p->ss7call) {
2387                         ss7_rel(p->ss7);
2388                         ast_mutex_unlock(&p->lock);
2389                         ast_log(LOG_ERROR, "Unable to allocate new SS7 call!\n");
2390                         return -1;
2391                 }
2392
2393                 called_nai_strip = 0;
2394                 ss7_called_nai = p->ss7->called_nai;
2395                 if (ss7_called_nai == SS7_NAI_DYNAMIC) { /* compute dynamically */
2396                         if (strncmp(c + p->stripmsd, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
2397                                 called_nai_strip = strlen(p->ss7->internationalprefix);
2398                                 ss7_called_nai = SS7_NAI_INTERNATIONAL;
2399                         } else if (strncmp(c + p->stripmsd, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
2400                                 called_nai_strip = strlen(p->ss7->nationalprefix);
2401                                 ss7_called_nai = SS7_NAI_NATIONAL;
2402                         } else {
2403                                 ss7_called_nai = SS7_NAI_SUBSCRIBER;
2404                         }
2405                 }
2406                 isup_set_called(p->ss7call, c + p->stripmsd + called_nai_strip, ss7_called_nai, p->ss7->ss7);
2407
2408                 calling_nai_strip = 0;
2409                 ss7_calling_nai = p->ss7->calling_nai;
2410                 if ((l != NULL) && (ss7_calling_nai == SS7_NAI_DYNAMIC)) { /* compute dynamically */
2411                         if (strncmp(l, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
2412                                 calling_nai_strip = strlen(p->ss7->internationalprefix);
2413                                 ss7_calling_nai = SS7_NAI_INTERNATIONAL;
2414                         } else if (strncmp(l, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
2415                                 calling_nai_strip = strlen(p->ss7->nationalprefix);
2416                                 ss7_calling_nai = SS7_NAI_NATIONAL;
2417                         } else {
2418                                 ss7_calling_nai = SS7_NAI_SUBSCRIBER;
2419                         }
2420                 }
2421                 isup_set_calling(p->ss7call, l ? (l + calling_nai_strip) : NULL, ss7_calling_nai,
2422                         p->use_callingpres ? cid_pres2ss7pres(ast->cid.cid_pres) : (l ? SS7_PRESENTATION_ALLOWED : SS7_PRESENTATION_RESTRICTED),
2423                         p->use_callingpres ? cid_pres2ss7screen(ast->cid.cid_pres) : SS7_SCREENING_USER_PROVIDED );
2424
2425                 isup_set_oli(p->ss7call, ast->cid.cid_ani2);
2426                 isup_init_call(p->ss7->ss7, p->ss7call, p->cic, p->dpc);
2427
2428                 ast_channel_lock(ast);
2429                 /* Set the charge number if it is set */
2430                 charge_str = pbx_builtin_getvar_helper(ast, "SS7_CHARGE_NUMBER");
2431                 if (charge_str)
2432                         isup_set_charge(p->ss7call, charge_str, SS7_ANI_CALLING_PARTY_SUB_NUMBER, 0x10);
2433                 
2434                 gen_address = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_ADDRESS");
2435                 if (gen_address)
2436                         isup_set_gen_address(p->ss7call, gen_address, p->gen_add_nai,p->gen_add_pres_ind, p->gen_add_num_plan,p->gen_add_type); /* need to add some types here for NAI,PRES,TYPE */
2437                 
2438                 gen_digits = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGITS");
2439                 gen_dig_type = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGTYPE");
2440                 gen_dig_scheme = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGSCHEME");
2441                 if (gen_digits)
2442                         isup_set_gen_digits(p->ss7call, gen_digits, atoi(gen_dig_type), atoi(gen_dig_scheme)); 
2443                 
2444                 gen_name = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_NAME");
2445                 if (gen_name)
2446                         isup_set_generic_name(p->ss7call, gen_name, GEN_NAME_TYPE_CALLING_NAME, GEN_NAME_AVAIL_AVAILABLE, GEN_NAME_PRES_ALLOWED);
2447
2448                 jip_digits = pbx_builtin_getvar_helper(ast, "SS7_JIP");
2449                 if (jip_digits)
2450                         isup_set_jip_digits(p->ss7call, jip_digits);
2451                 
2452                 lspi_ident = pbx_builtin_getvar_helper(ast, "SS7_LSPI_IDENT");
2453                 if (lspi_ident)
2454                         isup_set_lspi(p->ss7call, lspi_ident, 0x18, 0x7, 0x00); 
2455                 
2456                 rlt_flag = pbx_builtin_getvar_helper(ast, "SS7_RLT_ON");
2457                 if ((rlt_flag) && ((strncmp("NO", rlt_flag, strlen(rlt_flag))) != 0 )) {
2458                         isup_set_lspi(p->ss7call, rlt_flag, 0x18, 0x7, 0x00); /* Setting for Nortel DMS-250/500 */
2459                 }
2460                 
2461                 call_ref_id = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_IDENT");
2462                 call_ref_pc = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_PC");
2463                 if (call_ref_id && call_ref_pc) {
2464                         isup_set_callref(p->ss7call, atoi(call_ref_id),
2465                                          call_ref_pc ? atoi(call_ref_pc) : 0);
2466                 }
2467                 
2468                 send_far = pbx_builtin_getvar_helper(ast, "SS7_SEND_FAR");
2469                 if ((send_far) && ((strncmp("NO", send_far, strlen(send_far))) != 0 ))
2470                         (isup_far(p->ss7->ss7, p->ss7call));
2471                 
2472                 ast_channel_unlock(ast);
2473
2474                 isup_iam(p->ss7->ss7, p->ss7call);
2475                 ast_setstate(ast, AST_STATE_DIALING);
2476                 ss7_rel(p->ss7);
2477         }
2478 #endif /* HAVE_SS7 */
2479 #ifdef HAVE_PRI
2480         if (p->pri) {
2481                 struct pri_sr *sr;
2482 #ifdef SUPPORT_USERUSER
2483                 const char *useruser;
2484 #endif
2485                 int pridialplan;
2486                 int dp_strip;
2487                 int prilocaldialplan;
2488                 int ldp_strip;
2489                 int exclusive;
2490                 const char *rr_str;
2491                 int redirect_reason;
2492
2493                 c = strchr(dest, '/');
2494                 if (c)
2495                         c++;
2496                 else
2497                         c = dest;
2498
2499                 l = NULL;
2500                 n = NULL;
2501
2502                 if (!p->hidecallerid) {
2503                         l = ast->cid.cid_num;
2504                         if (!p->hidecalleridname) {
2505                                 n = ast->cid.cid_name;
2506                         }
2507                 }
2508
2509                 if (strlen(c) < p->stripmsd) {
2510                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2511                         ast_mutex_unlock(&p->lock);
2512                         return -1;
2513                 }
2514                 if (mysig != SIG_FXSKS) {
2515                         p->dop.op = DAHDI_DIAL_OP_REPLACE;
2516                         s = strchr(c + p->stripmsd, 'w');
2517                         if (s) {
2518                                 if (strlen(s) > 1)
2519                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2520                                 else
2521                                         p->dop.dialstr[0] = '\0';
2522                                 *s = '\0';
2523                         } else {
2524                                 p->dop.dialstr[0] = '\0';
2525                         }
2526                 }
2527                 if (pri_grab(p, p->pri)) {
2528                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2529                         ast_mutex_unlock(&p->lock);
2530                         return -1;
2531                 }
2532                 if (!(p->call = pri_new_call(p->pri->pri))) {
2533                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2534                         pri_rel(p->pri);
2535                         ast_mutex_unlock(&p->lock);
2536                         return -1;
2537                 }
2538                 if (!(sr = pri_sr_new())) {
2539                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2540                         pri_rel(p->pri);
2541                         ast_mutex_unlock(&p->lock);
2542                 }
2543                 if (p->bearer || (mysig == SIG_FXSKS)) {
2544                         if (p->bearer) {
2545                                 ast_debug(1, "Oooh, I have a bearer on %d (%d:%d)\n", PVT_TO_CHANNEL(p->bearer), p->bearer->logicalspan, p->bearer->channel);
2546                                 p->bearer->call = p->call;
2547                         } else
2548                                 ast_debug(1, "I'm being setup with no bearer right now...\n");
2549
2550                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2551                 }
2552                 p->digital = IS_DIGITAL(ast->transfercapability);
2553                 /* Add support for exclusive override */
2554                 if (p->priexclusive)
2555                         exclusive = 1;
2556                 else {
2557                 /* otherwise, traditional behavior */
2558                         if (p->pri->nodetype == PRI_NETWORK)
2559                                 exclusive = 0;
2560                         else
2561                                 exclusive = 1;
2562                 }
2563                 
2564                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2565                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
2566                                         (p->digital ? -1 : 
2567                                                 ((p->law == DAHDI_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2568                 if (p->pri->facilityenable)
2569                         pri_facility_enable(p->pri->pri);
2570
2571                 ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2572                 dp_strip = 0;
2573                 pridialplan = p->pri->dialplan - 1;
2574                 if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
2575                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2576                                 if (pridialplan == -2) {
2577                                         dp_strip = strlen(p->pri->internationalprefix);
2578                                 }
2579                                 pridialplan = PRI_INTERNATIONAL_ISDN;
2580                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2581                                 if (pridialplan == -2) {
2582                                         dp_strip = strlen(p->pri->nationalprefix);
2583                                 }
2584                                 pridialplan = PRI_NATIONAL_ISDN;
2585                         } else {
2586                                 pridialplan = PRI_LOCAL_ISDN;
2587                         }
2588                 }
2589                 while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
2590                         switch (c[p->stripmsd]) {
2591                         case 'U':
2592                                 pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
2593                                 break;
2594                         case 'I':
2595                                 pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
2596                                 break;
2597                         case 'N':
2598                                 pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
2599                                 break;
2600                         case 'L':
2601                                 pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
2602                                 break;
2603                         case 'S':
2604                                 pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
2605                                 break;
2606                         case 'V':
2607                                 pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
2608                                 break;
2609                         case 'R':
2610                                 pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
2611                                 break;
2612                         case 'u':
2613                                 pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
2614                                 break;
2615                         case 'e':
2616                                 pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
2617                                 break;
2618                         case 'x':
2619                                 pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
2620                                 break;
2621                         case 'f':
2622                                 pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
2623                                 break;
2624                         case 'n':
2625                                 pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
2626                                 break;
2627                         case 'p':
2628                                 pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
2629                                 break;
2630                         case 'r':
2631                                 pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
2632                                 break;
2633                         default:
2634                                 if (isalpha(*c))
2635                                         ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n", *c > 'Z' ? "NPI" : "TON", *c);
2636                         }
2637                         c++;
2638                 }
2639                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2640
2641                 ldp_strip = 0;
2642                 prilocaldialplan = p->pri->localdialplan - 1;
2643                 if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
2644                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2645                                 if (prilocaldialplan == -2) {
2646                                         ldp_strip = strlen(p->pri->internationalprefix);
2647                                 }
2648                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2649                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2650                                 if (prilocaldialplan == -2) {
2651                                         ldp_strip = strlen(p->pri->nationalprefix);
2652                                 }
2653                                 prilocaldialplan = PRI_NATIONAL_ISDN;
2654                         } else {
2655                                 prilocaldialplan = PRI_LOCAL_ISDN;
2656                         }
2657                 }
2658                 if (l != NULL) {
2659                         while (*l > '9' && *l != '*' && *l != '#') {
2660                                 switch (*l) {
2661                                 case 'U':
2662                                         prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
2663                                         break;
2664                                 case 'I':
2665                                         prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
2666                                         break;
2667                                 case 'N':
2668                                         prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
2669                                         break;
2670                                 case 'L':
2671                                         prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
2672                                         break;
2673                                 case 'S':
2674                                         prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
2675                                         break;
2676                                 case 'V':
2677                                         prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
2678                                         break;
2679                                 case 'R':
2680                                         prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
2681                                         break;
2682                                 case 'u':
2683                                         prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
2684                                         break;
2685                                 case 'e':
2686                                         prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
2687                                         break;
2688                                 case 'x':
2689                                         prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
2690                                         break;
2691                                 case 'f':
2692                                         prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
2693                                         break;
2694                                 case 'n':
2695                                         prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
2696                                         break;
2697                                 case 'p':
2698                                         prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
2699                                         break;
2700                                 case 'r':
2701                                         prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
2702                                         break;
2703                                 default:
2704                                         if (isalpha(*l))
2705                                                 ast_log(LOG_WARNING, "Unrecognized prilocaldialplan %s modifier: %c\n", *c > 'Z' ? "NPI" : "TON", *c);
2706                                 }
2707                                 l++;
2708                         }
2709                 }
2710                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2711                         p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2712                 if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2713                         if (!strcasecmp(rr_str, "UNKNOWN"))
2714                                 redirect_reason = 0;
2715                         else if (!strcasecmp(rr_str, "BUSY"))
2716                                 redirect_reason = 1;
2717                         else if (!strcasecmp(rr_str, "NO_REPLY"))
2718                                 redirect_reason = 2;
2719                         else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2720                                 redirect_reason = 15;
2721                         else
2722                                 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2723                 } else
2724                         redirect_reason = PRI_REDIR_UNCONDITIONAL;
2725                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2726
2727 #ifdef SUPPORT_USERUSER
2728                 /* User-user info */
2729                 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2730
2731                 if (useruser)
2732                         pri_sr_set_useruser(sr, useruser);
2733 #endif
2734
2735                 if (pri_setup(p->pri->pri, p->call, sr)) {
2736                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
2737                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2738                         pri_rel(p->pri);
2739                         ast_mutex_unlock(&p->lock);
2740                         pri_sr_free(sr);
2741                         return -1;
2742                 }
2743                 pri_sr_free(sr);
2744                 ast_setstate(ast, AST_STATE_DIALING);
2745                 pri_rel(p->pri);
2746         }
2747 #endif          
2748         ast_mutex_unlock(&p->lock);
2749         return 0;
2750 }
2751
2752 static void destroy_dahdi_pvt(struct dahdi_pvt **pvt)
2753 {
2754         struct dahdi_pvt *p = *pvt;
2755         /* Remove channel from the list */
2756         if (p->prev)
2757                 p->prev->next = p->next;
2758         if (p->next)
2759                 p->next->prev = p->prev;
2760         if (p->use_smdi)
2761                 ast_smdi_interface_unref(p->smdi_iface);
2762         if (p->mwi_event_sub)
2763                 ast_event_unsubscribe(p->mwi_event_sub);
2764         if (p->vars)
2765                 ast_variables_destroy(p->vars);
2766         ast_mutex_destroy(&p->lock);
2767         ast_free(p);
2768         *pvt = NULL;
2769 }
2770
2771 static int destroy_channel(struct dahdi_pvt *prev, struct dahdi_pvt *cur, int now)
2772 {
2773         int owned = 0;
2774         int i = 0;
2775
2776         if (!now) {
2777                 if (cur->owner) {
2778                         owned = 1;
2779                 }
2780
2781                 for (i = 0; i < 3; i++) {
2782                         if (cur->subs[i].owner) {
2783                                 owned = 1;
2784                         }
2785                 }
2786                 if (!owned) {
2787                         if (prev) {
2788                                 prev->next = cur->next;
2789                                 if (prev->next)
2790                                         prev->next->prev = prev;
2791                                 else
2792                                         ifend = prev;
2793                         } else {
2794                                 iflist = cur->next;
2795                                 if (iflist)
2796                                         iflist->prev = NULL;
2797                                 else
2798                                         ifend = NULL;
2799                         }
2800                         if (cur->subs[SUB_REAL].zfd > -1) {
2801                                 dahdi_close(cur->subs[SUB_REAL].zfd);
2802                         }
2803                         destroy_dahdi_pvt(&cur);
2804                 }
2805         } else {
2806                 if (prev) {
2807                         prev->next = cur->next;
2808                         if (prev->next)
2809                                 prev->next->prev = prev;
2810                         else
2811                                 ifend = prev;
2812                 } else {
2813                         iflist = cur->next;
2814                         if (iflist)
2815                                 iflist->prev = NULL;
2816                         else
2817                                 ifend = NULL;
2818                 }
2819                 if (cur->subs[SUB_REAL].zfd > -1) {
2820                         dahdi_close(cur->subs[SUB_REAL].zfd);
2821                 }
2822                 destroy_dahdi_pvt(&cur);
2823         }
2824         return 0;
2825 }
2826
2827 #ifdef HAVE_PRI
2828 static char *dahdi_send_keypad_facility_app = "DAHDISendKeypadFacility";
2829
2830 static char *dahdi_send_keypad_facility_synopsis = "Send digits out of band over a PRI";
2831
2832 static char *dahdi_send_keypad_facility_descrip = 
2833 "  DAHDISendKeypadFacility(): This application will send the given string of digits in a Keypad Facility\n"
2834 "  IE over the current channel.\n";
2835
2836 static int dahdi_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2837 {
2838         /* Data will be our digit string */
2839         struct dahdi_pvt *p;
2840         char *digits = (char *) data;
2841
2842         if (ast_strlen_zero(digits)) {
2843                 ast_debug(1, "No digit string sent to application!\n");
2844                 return -1;
2845         }
2846
2847         p = (struct dahdi_pvt *)chan->tech_pvt;
2848
2849         if (!p) {
2850                 ast_debug(1, "Unable to find technology private\n");
2851                 return -1;
2852         }
2853
2854         ast_mutex_lock(&p->lock);
2855
2856         if (!p->pri || !p->call) {
2857                 ast_debug(1, "Unable to find pri or call on channel!\n");
2858                 ast_mutex_unlock(&p->lock);
2859                 return -1;
2860         }
2861
2862         if (!pri_grab(p, p->pri)) {
2863                 pri_keypad_facility(p->pri->pri, p->call, digits);
2864                 pri_rel(p->pri);
2865         } else {
2866                 ast_debug(1, "Unable to grab pri to send keypad facility!\n");
2867                 ast_mutex_unlock(&p->lock);
2868                 return -1;
2869         }
2870
2871         ast_mutex_unlock(&p->lock);
2872
2873         return 0;
2874 }
2875
2876 static int pri_is_up(struct dahdi_pri *pri)
2877 {
2878         int x;
2879         for (x = 0; x < NUM_DCHANS; x++) {
2880                 if (pri->dchanavail[x] == DCHAN_AVAILABLE)
2881                         return 1;
2882         }
2883         return 0;
2884 }
2885
2886 static int pri_assign_bearer(struct dahdi_pvt *crv, struct dahdi_pri *pri, struct dahdi_pvt *bearer)
2887 {
2888         bearer->owner = &inuse;
2889         bearer->realcall = crv;
2890         crv->subs[SUB_REAL].zfd = bearer->subs[SUB_REAL].zfd;
2891         if (crv->subs[SUB_REAL].owner)
2892                 ast_channel_set_fd(crv->subs[SUB_REAL].owner, 0, crv->subs[SUB_REAL].zfd);
2893         crv->bearer = bearer;
2894         crv->call = bearer->call;
2895         crv->pri = pri;
2896         return 0;
2897 }
2898
2899 static char *pri_order(int level)
2900 {
2901         switch (level) {
2902         case 0:
2903                 return "Primary";
2904         case 1:
2905                 return "Secondary";
2906         case 2:
2907                 return "Tertiary";
2908         case 3:
2909                 return "Quaternary";
2910         default:
2911                 return "<Unknown>";
2912         }               
2913 }
2914
2915 /* Returns fd of the active dchan */
2916 static int pri_active_dchan_fd(struct dahdi_pri *pri)
2917 {
2918         int x = -1;
2919
2920         for (x = 0; x < NUM_DCHANS; x++) {
2921                 if ((pri->dchans[x] == pri->pri))
2922                         break;
2923         }
2924
2925         return pri->fds[x];
2926 }
2927
2928 static int pri_find_dchan(struct dahdi_pri *pri)
2929 {
2930         int oldslot = -1;
2931         struct pri *old;
2932         int newslot = -1;
2933         int x;
2934         old = pri->pri;
2935         for (x = 0; x < NUM_DCHANS; x++) {
2936                 if ((pri->dchanavail[x] == DCHAN_AVAILABLE) && (newslot < 0))
2937                         newslot = x;
2938                 if (pri->dchans[x] == old) {
2939                         oldslot = x;
2940                 }
2941         }
2942         if (newslot < 0) {
2943                 newslot = 0;
2944                 ast_log(LOG_WARNING, "No D-channels available!  Using Primary channel %d as D-channel anyway!\n",
2945                         pri->dchannels[newslot]);
2946         }
2947         if (old && (oldslot != newslot))
2948                 ast_log(LOG_NOTICE, "Switching from from d-channel %d to channel %d!\n",
2949                         pri->dchannels[oldslot], pri->dchannels[newslot]);
2950         pri->pri = pri->dchans[newslot];
2951         return 0;
2952 }
2953 #endif
2954
2955 static int dahdi_hangup(struct ast_channel *ast)
2956 {
2957         int res;
2958         int index,x, law;
2959         /*static int restore_gains(struct dahdi_pvt *p);*/
2960         struct dahdi_pvt *p = ast->tech_pvt;
2961         struct dahdi_pvt *tmp = NULL;
2962         struct dahdi_pvt *prev = NULL;
2963         DAHDI_PARAMS par;
2964
2965         ast_debug(1, "dahdi_hangup(%s)\n", ast->name);
2966         if (!ast->tech_pvt) {
2967                 ast_log(LOG_WARNING, "Asked to hangup channel not connected\n");
2968                 return 0;
2969         }
2970         
2971         ast_mutex_lock(&p->lock);
2972         
2973         index = dahdi_get_index(ast, p, 1);
2974
2975         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
2976                 x = 1;
2977                 ast_channel_setoption(ast,AST_OPTION_AUDIO_MODE,&x,sizeof(char),0);
2978         }
2979
2980         x = 0;
2981         dahdi_confmute(p, 0);
2982         p->muting = 0;
2983         restore_gains(p);
2984         if (p->origcid_num) {
2985                 ast_copy_string(p->cid_num, p->origcid_num, sizeof(p->cid_num));
2986                 ast_free(p->origcid_num);
2987                 p->origcid_num = NULL;
2988         }       
2989         if (p->origcid_name) {
2990                 ast_copy_string(p->cid_name, p->origcid_name, sizeof(p->cid_name));
2991                 ast_free(p->origcid_name);
2992                 p->origcid_name = NULL;
2993         }       
2994         if (p->dsp)
2995                 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
2996         if (p->exten)
2997                 p->exten[0] = '\0';
2998
2999         ast_debug(1, "Hangup: channel: %d index = %d, normal = %d, callwait = %d, thirdcall = %d\n",
3000                 p->channel, index, p->subs[SUB_REAL].zfd, p->subs[SUB_CALLWAIT].zfd, p->subs[SUB_THREEWAY].zfd);
3001         p->ignoredtmf = 0;
3002         
3003         if (index > -1) {
3004                 /* Real channel, do some fixup */
3005                 p->subs[index].owner = NULL;
3006                 p->subs[index].needanswer = 0;
3007                 p->subs[index].needflash = 0;
3008                 p->subs[index].needringing = 0;
3009                 p->subs[index].needbusy = 0;
3010                 p->subs[index].needcongestion = 0;
3011                 p->subs[index].linear = 0;
3012                 p->subs[index].needcallerid = 0;
3013                 p->polarity = POLARITY_IDLE;
3014                 dahdi_setlinear(p->subs[index].zfd, 0);
3015                 if (index == SUB_REAL) {
3016                         if ((p->subs[SUB_CALLWAIT].zfd > -1) && (p->subs[SUB_THREEWAY].zfd > -1)) {
3017                                 ast_debug(1, "Normal call hung up with both three way call and a call waiting call in place?\n");
3018                                 if (p->subs[SUB_CALLWAIT].inthreeway) {
3019                                         /* We had flipped over to answer a callwait and now it's gone */
3020                                         ast_debug(1, "We were flipped over to the callwait, moving back and unowning.\n");
3021                                         /* Move to the call-wait, but un-own us until they flip back. */
3022                                         swap_subs(p, SUB_CALLWAIT, SUB_REAL);
3023                                         unalloc_sub(p, SUB_CALLWAIT);
3024                                         p->owner = NULL;
3025                                 } else {
3026                                         /* The three way hung up, but we still have a call wait */
3027                                         ast_debug(1, "We were in the threeway and have a callwait still.  Ditching the threeway.\n");
3028                                         swap_subs(p, SUB_THREEWAY, SUB_REAL);
3029                                         unalloc_sub(p, SUB_THREEWAY);
3030                                         if (p->subs[SUB_REAL].inthreeway) {
3031                                                 /* This was part of a three way call.  Immediately make way for
3032                                                    another call */
3033                                                 ast_debug(1, "Call was complete, setting owner to former third call\n");
3034                                                 p->owner = p->subs[SUB_REAL].owner;
3035                                         } else {
3036                                                 /* This call hasn't been completed yet...  Set owner to NULL */
3037                                                 ast_debug(1, "Call was incomplete, setting owner to NULL\n");
3038                                                 p->owner = NULL;
3039                                         }
3040                                         p->subs[SUB_REAL].inthreeway = 0;
3041                                 }
3042                         } else if (p->subs[SUB_CALLWAIT].zfd > -1) {
3043      &