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