4752294e55059a6ceb3ac4e9c58edacafa8fc8be
[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_LOGICAL      0
302 #define DAHDI_CHAN_MAPPING_PHYSICAL     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         struct timeval flashtime;                       /*!< Last flash-hook time */
716         struct ast_dsp *dsp;
717         int cref;                                       /*!< Call reference number */
718         struct dahdi_dialoperation dop;
719         int whichwink;                                  /*!< SIG_FEATDMF_TA Which wink are we on? */
720         char finaldial[64];
721         char accountcode[AST_MAX_ACCOUNT_CODE];         /*!< Account code */
722         int amaflags;                                   /*!< AMA Flags */
723         struct tdd_state *tdd;                          /*!< TDD flag */
724         char call_forward[AST_MAX_EXTENSION];
725         char mailbox[AST_MAX_EXTENSION];
726         struct ast_event_sub *mwi_event_sub;
727         char dialdest[256];
728         int onhooktime;
729         int msgstate;
730         int distinctivering;                            /*!< Which distinctivering to use */
731         int cidrings;                                   /*!< Which ring to deliver CID on */
732         int dtmfrelax;                                  /*!< whether to run in relaxed DTMF mode */
733         int fake_event;
734         int polarityonanswerdelay;
735         struct timeval polaritydelaytv;
736         int sendcalleridafter;
737 #ifdef HAVE_PRI
738         struct dahdi_pri *pri;
739         struct dahdi_pvt *bearer;
740         struct dahdi_pvt *realcall;
741         q931_call *call;
742         int prioffset;
743         int logicalspan;
744 #endif  
745         int polarity;
746         int dsp_features;
747 #ifdef HAVE_SS7
748         struct dahdi_ss7 *ss7;
749         struct isup_call *ss7call;
750         char charge_number[50];
751         char gen_add_number[50];
752         char gen_dig_number[50];
753         char orig_called_num[50];
754         char redirecting_num[50];
755         char generic_name[50];
756         unsigned char gen_add_num_plan;
757         unsigned char gen_add_nai;
758         unsigned char gen_add_pres_ind;
759         unsigned char gen_add_type;
760         unsigned char gen_dig_type;
761         unsigned char gen_dig_scheme;
762         char jip_number[50];
763         unsigned char lspi_type;
764         unsigned char lspi_scheme;
765         unsigned char lspi_context;
766         char lspi_ident[50];
767         unsigned int call_ref_ident;
768         unsigned int call_ref_pc;
769         unsigned char calling_party_cat;
770         int transcap;
771         int cic;                                                        /*!< CIC associated with channel */
772         unsigned int dpc;                                               /*!< CIC's DPC */
773         unsigned int loopedback:1;
774 #endif
775         char begindigit;
776         int muting;
777 } *iflist = NULL, *ifend = NULL;
778
779 /*! \brief Channel configuration from chan_dahdi.conf .
780  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
781  * Generally there is a field here for every possible configuration item.
782  *
783  * The state of fields is saved along the parsing and whenever a 'channel'
784  * statement is reached, the current dahdi_chan_conf is used to configure the 
785  * channel (struct dahdi_pvt)
786  *
787  * \see dahdi_chan_init for the default values.
788  */
789 struct dahdi_chan_conf {
790         struct dahdi_pvt chan;
791 #ifdef HAVE_PRI
792         struct dahdi_pri pri;
793 #endif
794
795 #ifdef HAVE_SS7
796         struct dahdi_ss7 ss7;
797 #endif
798         struct dahdi_params timing;
799         int is_sig_auto; /*!< Use channel signalling from DAHDI? */
800
801         char smdi_port[SMDI_MAX_FILENAME_LEN];
802 };
803
804 /*! returns a new dahdi_chan_conf with default values (by-value) */
805 static struct dahdi_chan_conf dahdi_chan_conf_default(void) {
806         /* recall that if a field is not included here it is initialized
807          * to 0 or equivalent
808          */
809         struct dahdi_chan_conf conf = {
810 #ifdef HAVE_PRI
811                 .pri = {
812                         .nsf = PRI_NSF_NONE,
813                         .switchtype = PRI_SWITCH_NI2,
814                         .dialplan = PRI_UNKNOWN + 1,
815                         .localdialplan = PRI_NATIONAL_ISDN + 1,
816                         .nodetype = PRI_CPE,
817
818                         .minunused = 2,
819                         .idleext = "",
820                         .idledial = "",
821                         .internationalprefix = "",
822                         .nationalprefix = "",
823                         .localprefix = "",
824                         .privateprefix = "",
825                         .unknownprefix = "",
826                         .resetinterval = -1,
827                 },
828 #endif
829 #ifdef HAVE_SS7
830                 .ss7 = {
831                         .called_nai = SS7_NAI_NATIONAL,
832                         .calling_nai = SS7_NAI_NATIONAL,
833                         .internationalprefix = "",
834                         .nationalprefix = "",
835                         .subscriberprefix = "",
836                         .unknownprefix = ""
837                 },
838 #endif
839                 .chan = {
840                         .context = "default",
841                         .cid_num = "",
842                         .cid_name = "",
843                         .mohinterpret = "default",
844                         .mohsuggest = "",
845                         .parkinglot = "",
846                         .transfertobusy = 1,
847
848                         .cid_signalling = CID_SIG_BELL,
849                         .cid_start = CID_START_RING,
850                         .dahditrcallerid = 0,
851                         .use_callerid = 1,
852                         .sig = -1,
853                         .outsigmod = -1,
854
855                         .cid_rxgain = +5.0,
856
857                         .tonezone = -1,
858
859                         .echocancel.head.tap_length = 1,
860
861                         .busycount = 3,
862
863                         .accountcode = "",
864
865                         .mailbox = "",
866
867
868                         .polarityonanswerdelay = 600,
869
870                         .sendcalleridafter = DEFAULT_CIDRINGS,
871                 
872                         .buf_policy = DAHDI_POLICY_IMMEDIATE,
873                         .buf_no = numbufs
874                 },
875                 .timing = {
876                         .prewinktime = -1,
877                         .preflashtime = -1,
878                         .winktime = -1,
879                         .flashtime = -1,
880                         .starttime = -1,
881                         .rxwinktime = -1,
882                         .rxflashtime = -1,
883                         .debouncetime = -1
884                 },
885                 .is_sig_auto = 1,
886                 .smdi_port = "/dev/ttyS0",
887         };
888
889         return conf;
890 }
891
892
893 static struct ast_channel *dahdi_request(const char *type, int format, void *data, int *cause);
894 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
895 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
896 static int dahdi_sendtext(struct ast_channel *c, const char *text);
897 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
898 static int dahdi_hangup(struct ast_channel *ast);
899 static int dahdi_answer(struct ast_channel *ast);
900 static struct ast_frame *dahdi_read(struct ast_channel *ast);
901 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
902 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
903 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
904 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
905 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
906 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
907 static int handle_init_event(struct dahdi_pvt *i, int event);
908
909 static const struct ast_channel_tech dahdi_tech = {
910         .type = "DAHDI",
911         .description = tdesc,
912         .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
913         .requester = dahdi_request,
914         .send_digit_begin = dahdi_digit_begin,
915         .send_digit_end = dahdi_digit_end,
916         .send_text = dahdi_sendtext,
917         .call = dahdi_call,
918         .hangup = dahdi_hangup,
919         .answer = dahdi_answer,
920         .read = dahdi_read,
921         .write = dahdi_write,
922         .bridge = dahdi_bridge,
923         .exception = dahdi_exception,
924         .indicate = dahdi_indicate,
925         .fixup = dahdi_fixup,
926         .setoption = dahdi_setoption,
927         .func_channel_read = dahdi_func_read,
928 };
929
930 #ifdef HAVE_PRI
931 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
932 #else
933 #define GET_CHANNEL(p) ((p)->channel)
934 #endif
935
936 struct dahdi_pvt *round_robin[32];
937
938 #ifdef HAVE_PRI
939 static inline int pri_grab(struct dahdi_pvt *pvt, struct dahdi_pri *pri)
940 {
941         int res;
942         /* Grab the lock first */
943         do {
944                 res = ast_mutex_trylock(&pri->lock);
945                 if (res) {
946                         DEADLOCK_AVOIDANCE(&pvt->lock);
947                 }
948         } while (res);
949         /* Then break the poll */
950         if (pri->master != AST_PTHREADT_NULL)
951                 pthread_kill(pri->master, SIGURG);
952         return 0;
953 }
954 #endif
955
956 #ifdef HAVE_SS7
957 static inline void ss7_rel(struct dahdi_ss7 *ss7)
958 {
959         ast_mutex_unlock(&ss7->lock);
960 }
961
962 static inline int ss7_grab(struct dahdi_pvt *pvt, struct dahdi_ss7 *pri)
963 {
964         int res;
965         /* Grab the lock first */
966         do {
967                 res = ast_mutex_trylock(&pri->lock);
968                 if (res) {
969                         DEADLOCK_AVOIDANCE(&pvt->lock);
970                 }
971         } while (res);
972         /* Then break the poll */
973         if (pri->master != AST_PTHREADT_NULL)
974                 pthread_kill(pri->master, SIGURG);
975         return 0;
976 }
977 #endif
978 #define NUM_CADENCE_MAX 25
979 static int num_cadence = 4;
980 static int user_has_defined_cadences = 0;
981
982 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
983         { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
984         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
985         { { 125, 125, 125, 125, 125, 4000 } },  /*!< Three short bursts */
986         { { 1000, 500, 2500, 5000 } },  /*!< Long ring */
987 };
988
989 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
990  * is 1, the second pause is 2 and so on.
991  */
992
993 static int cidrings[NUM_CADENCE_MAX] = {
994         2,                                                                              /*!< Right after first long ring */
995         4,                                                                              /*!< Right after long part */
996         3,                                                                              /*!< After third chirp */
997         2,                                                                              /*!< Second spell */
998 };
999
1000 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
1001 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
1002
1003 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
1004                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
1005
1006 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
1007 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
1008
1009 static int dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok)
1010 {
1011         int res;
1012         if (p->subs[SUB_REAL].owner == ast)
1013                 res = 0;
1014         else if (p->subs[SUB_CALLWAIT].owner == ast)
1015                 res = 1;
1016         else if (p->subs[SUB_THREEWAY].owner == ast)
1017                 res = 2;
1018         else {
1019                 res = -1;
1020                 if (!nullok)
1021                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
1022         }
1023         return res;
1024 }
1025
1026 #ifdef HAVE_PRI
1027 static void wakeup_sub(struct dahdi_pvt *p, int a, struct dahdi_pri *pri)
1028 #else
1029 static void wakeup_sub(struct dahdi_pvt *p, int a, void *pri)
1030 #endif
1031 {
1032 #ifdef HAVE_PRI
1033         if (pri)
1034                 ast_mutex_unlock(&pri->lock);
1035 #endif                  
1036         for (;;) {
1037                 if (p->subs[a].owner) {
1038                         if (ast_channel_trylock(p->subs[a].owner)) {
1039                                 DEADLOCK_AVOIDANCE(&p->lock);
1040                         } else {
1041                                 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
1042                                 ast_channel_unlock(p->subs[a].owner);
1043                                 break;
1044                         }
1045                 } else
1046                         break;
1047         }
1048 #ifdef HAVE_PRI
1049         if (pri)
1050                 ast_mutex_lock(&pri->lock);
1051 #endif                  
1052 }
1053
1054 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f, void *data)
1055 {
1056 #ifdef HAVE_PRI
1057         struct dahdi_pri *pri = (struct dahdi_pri*) data;
1058 #endif
1059 #ifdef HAVE_SS7
1060         struct dahdi_ss7 *ss7 = (struct dahdi_ss7*) data;
1061 #endif
1062         /* We must unlock the PRI to avoid the possibility of a deadlock */
1063 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1064         if (data) {
1065                 switch (p->sig) {
1066 #ifdef HAVE_PRI
1067                 case SIG_BRI:
1068                 case SIG_BRI_PTMP:
1069                 case SIG_PRI:
1070                         ast_mutex_unlock(&pri->lock);
1071                         break;
1072 #endif
1073 #ifdef HAVE_SS7
1074                 case SIG_SS7:
1075                         ast_mutex_unlock(&ss7->lock);
1076                         break;
1077 #endif
1078                 default:
1079                         break;
1080                 }
1081         }
1082 #endif          
1083         for (;;) {
1084                 if (p->owner) {
1085                         if (ast_channel_trylock(p->owner)) {
1086                                 DEADLOCK_AVOIDANCE(&p->lock);
1087                         } else {
1088                                 ast_queue_frame(p->owner, f);
1089                                 ast_channel_unlock(p->owner);
1090                                 break;
1091                         }
1092                 } else
1093                         break;
1094         }
1095 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1096         if (data) {
1097                 switch (p->sig) {
1098 #ifdef HAVE_PRI
1099                 case SIG_BRI:
1100                 case SIG_BRI_PTMP:
1101                 case SIG_PRI:
1102                         ast_mutex_lock(&pri->lock);
1103                         break;
1104 #endif
1105 #ifdef HAVE_SS7
1106                 case SIG_SS7:
1107                         ast_mutex_lock(&ss7->lock);
1108                         break;
1109 #endif
1110                 default:
1111                         break;
1112                 }
1113         }
1114
1115 #endif          
1116 }
1117
1118 static int restore_gains(struct dahdi_pvt *p);
1119
1120 static void swap_subs(struct dahdi_pvt *p, int a, int b)
1121 {
1122         int tchan;
1123         int tinthreeway;
1124         struct ast_channel *towner;
1125
1126         ast_debug(1, "Swapping %d and %d\n", a, b);
1127
1128         tchan = p->subs[a].chan;
1129         towner = p->subs[a].owner;
1130         tinthreeway = p->subs[a].inthreeway;
1131
1132         p->subs[a].chan = p->subs[b].chan;
1133         p->subs[a].owner = p->subs[b].owner;
1134         p->subs[a].inthreeway = p->subs[b].inthreeway;
1135
1136         p->subs[b].chan = tchan;
1137         p->subs[b].owner = towner;
1138         p->subs[b].inthreeway = tinthreeway;
1139
1140         if (p->subs[a].owner) 
1141                 ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
1142         if (p->subs[b].owner) 
1143                 ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
1144         wakeup_sub(p, a, NULL);
1145         wakeup_sub(p, b, NULL);
1146 }
1147
1148 static int dahdi_open(char *fn)
1149 {
1150         int fd;
1151         int isnum;
1152         int chan = 0;
1153         int bs;
1154         int x;
1155         isnum = 1;
1156         for (x = 0; x < strlen(fn); x++) {
1157                 if (!isdigit(fn[x])) {
1158                         isnum = 0;
1159                         break;
1160                 }
1161         }
1162         if (isnum) {
1163                 chan = atoi(fn);
1164                 if (chan < 1) {
1165                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
1166                         return -1;
1167                 }
1168                 fn = "/dev/dahdi/channel";
1169         }
1170         fd = open(fn, O_RDWR | O_NONBLOCK);
1171         if (fd < 0) {
1172                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
1173                 return -1;
1174         }
1175         if (chan) {
1176                 if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
1177                         x = errno;
1178                         close(fd);
1179                         errno = x;
1180                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
1181                         return -1;
1182                 }
1183         }
1184         bs = READ_SIZE;
1185         if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
1186                 ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
1187                 x = errno;
1188                 close(fd);
1189                 errno = x;
1190                 return -1;
1191         }
1192         return fd;
1193 }
1194
1195 static void dahdi_close(int fd)
1196 {
1197         if (fd > 0)
1198                 close(fd);
1199 }
1200
1201 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
1202 {
1203         dahdi_close(chan_pvt->subs[sub_num].dfd);
1204         chan_pvt->subs[sub_num].dfd = -1;
1205 }
1206
1207 #ifdef HAVE_PRI
1208 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
1209 {
1210         dahdi_close(pri->fds[fd_num]);
1211         pri->fds[fd_num] = -1;
1212 }
1213 #endif
1214
1215 #ifdef HAVE_SS7
1216 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
1217 {
1218         dahdi_close(ss7->fds[fd_num]);
1219         ss7->fds[fd_num] = -1;
1220 }
1221 #endif
1222
1223 static int dahdi_setlinear(int dfd, int linear)
1224 {
1225         int res;
1226         res = ioctl(dfd, DAHDI_SETLINEAR, &linear);
1227         if (res)
1228                 return res;
1229         return 0;
1230 }
1231
1232
1233 static int alloc_sub(struct dahdi_pvt *p, int x)
1234 {
1235         struct dahdi_bufferinfo bi;
1236         int res;
1237         if (p->subs[x].dfd >= 0) {
1238                 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
1239                 return -1;
1240         }
1241
1242         p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
1243         if (p->subs[x].dfd <= -1) {
1244                 ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
1245                 return -1;
1246         }
1247
1248         res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
1249         if (!res) {
1250                 bi.txbufpolicy = p->buf_policy;
1251                 bi.rxbufpolicy = p->buf_policy;
1252                 bi.numbufs = p->buf_no;
1253                 res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
1254                 if (res < 0) {
1255                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
1256                 }
1257         } else 
1258                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
1259
1260         if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
1261                 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
1262                 dahdi_close_sub(p, x);
1263                 p->subs[x].dfd = -1;
1264                 return -1;
1265         }
1266         ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
1267         return 0;
1268 }
1269
1270 static int unalloc_sub(struct dahdi_pvt *p, int x)
1271 {
1272         if (!x) {
1273                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
1274                 return -1;
1275         }
1276         ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
1277         dahdi_close_sub(p, x);
1278         p->subs[x].linear = 0;
1279         p->subs[x].chan = 0;
1280         p->subs[x].owner = NULL;
1281         p->subs[x].inthreeway = 0;
1282         p->polarity = POLARITY_IDLE;
1283         memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
1284         return 0;
1285 }
1286
1287 static int digit_to_dtmfindex(char digit)
1288 {
1289         if (isdigit(digit))
1290                 return DAHDI_TONE_DTMF_BASE + (digit - '0');
1291         else if (digit >= 'A' && digit <= 'D')
1292                 return DAHDI_TONE_DTMF_A + (digit - 'A');
1293         else if (digit >= 'a' && digit <= 'd')
1294                 return DAHDI_TONE_DTMF_A + (digit - 'a');
1295         else if (digit == '*')
1296                 return DAHDI_TONE_DTMF_s;
1297         else if (digit == '#')
1298                 return DAHDI_TONE_DTMF_p;
1299         else
1300                 return -1;
1301 }
1302
1303 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
1304 {
1305         struct dahdi_pvt *pvt;
1306         int idx;
1307         int dtmf = -1;
1308         
1309         pvt = chan->tech_pvt;
1310
1311         ast_mutex_lock(&pvt->lock);
1312
1313         idx = dahdi_get_index(chan, pvt, 0);
1314
1315         if ((idx != SUB_REAL) || !pvt->owner)
1316                 goto out;
1317
1318 #ifdef HAVE_PRI
1319         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP)) 
1320                         && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
1321                 if (pvt->setup_ack) {
1322                         if (!pri_grab(pvt, pvt->pri)) {
1323                                 pri_information(pvt->pri->pri, pvt->call, digit);
1324                                 pri_rel(pvt->pri);
1325                         } else
1326                                 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
1327                 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
1328                         int res;
1329                         ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n", digit);
1330                         res = strlen(pvt->dialdest);
1331                         pvt->dialdest[res++] = digit;
1332                         pvt->dialdest[res] = '\0';
1333                 }
1334                 goto out;
1335         }
1336 #endif
1337         if ((dtmf = digit_to_dtmfindex(digit)) == -1)
1338                 goto out;
1339
1340         if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
1341                 int res;
1342                 struct dahdi_dialoperation zo = {
1343                         .op = DAHDI_DIAL_OP_APPEND,
1344                 };
1345
1346                 zo.dialstr[0] = 'T';
1347                 zo.dialstr[1] = digit;
1348                 zo.dialstr[2] = '\0';
1349                 if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
1350                         ast_log(LOG_WARNING, "Couldn't dial digit %c: %s\n", digit, strerror(errno));
1351                 else
1352                         pvt->dialing = 1;
1353         } else {
1354                 ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
1355                 pvt->dialing = 1;
1356                 pvt->begindigit = digit;
1357         }
1358
1359 out:
1360         ast_mutex_unlock(&pvt->lock);
1361
1362         return 0;
1363 }
1364
1365 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
1366 {
1367         struct dahdi_pvt *pvt;
1368         int res = 0;
1369         int idx;
1370         int x;
1371         
1372         pvt = chan->tech_pvt;
1373
1374         ast_mutex_lock(&pvt->lock);
1375         
1376         idx = dahdi_get_index(chan, pvt, 0);
1377
1378         if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
1379                 goto out;
1380
1381 #ifdef HAVE_PRI
1382         /* This means that the digit was already sent via PRI signalling */
1383         if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
1384                         && !pvt->begindigit)
1385                 goto out;
1386 #endif
1387
1388         if (pvt->begindigit) {
1389                 x = -1;
1390                 ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
1391                 res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
1392                 pvt->dialing = 0;
1393                 pvt->begindigit = 0;
1394         }
1395
1396 out:
1397         ast_mutex_unlock(&pvt->lock);
1398
1399         return res;
1400 }
1401
1402 static char *events[] = {
1403         "No event",
1404         "On hook",
1405         "Ring/Answered",
1406         "Wink/Flash",
1407         "Alarm",
1408         "No more alarm",
1409         "HDLC Abort",
1410         "HDLC Overrun",
1411         "HDLC Bad FCS",
1412         "Dial Complete",
1413         "Ringer On",
1414         "Ringer Off",
1415         "Hook Transition Complete",
1416         "Bits Changed",
1417         "Pulse Start",
1418         "Timer Expired",
1419         "Timer Ping",
1420         "Polarity Reversal",
1421         "Ring Begin",
1422 };
1423
1424 static struct {
1425         int alarm;
1426         char *name;
1427 } alarms[] = {
1428         { DAHDI_ALARM_RED, "Red Alarm" },
1429         { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
1430         { DAHDI_ALARM_BLUE, "Blue Alarm" },
1431         { DAHDI_ALARM_RECOVER, "Recovering" },
1432         { DAHDI_ALARM_LOOPBACK, "Loopback" },
1433         { DAHDI_ALARM_NOTOPEN, "Not Open" },
1434         { DAHDI_ALARM_NONE, "None" },
1435 };
1436
1437 static char *alarm2str(int alm)
1438 {
1439         int x;
1440         for (x = 0; x < ARRAY_LEN(alarms); x++) {
1441                 if (alarms[x].alarm & alm)
1442                         return alarms[x].name;
1443         }
1444         return alm ? "Unknown Alarm" : "No Alarm";
1445 }
1446
1447 static char *event2str(int event)
1448 {
1449         static char buf[256];
1450         if ((event < (ARRAY_LEN(events))) && (event > -1))
1451                 return events[event];
1452         sprintf(buf, "Event %d", event); /* safe */
1453         return buf;
1454 }
1455
1456 #ifdef HAVE_PRI
1457 static char *dialplan2str(int dialplan)
1458 {
1459         if (dialplan == -1 || dialplan == -2) {
1460                 return("Dynamically set dialplan in ISDN");
1461         }
1462         return (pri_plan2str(dialplan));
1463 }
1464 #endif
1465
1466 static char *dahdi_sig2str(int sig)
1467 {
1468         static char buf[256];
1469         switch (sig) {
1470         case SIG_EM:
1471                 return "E & M Immediate";
1472         case SIG_EMWINK:
1473                 return "E & M Wink";
1474         case SIG_EM_E1:
1475                 return "E & M E1";
1476         case SIG_FEATD:
1477                 return "Feature Group D (DTMF)";
1478         case SIG_FEATDMF:
1479                 return "Feature Group D (MF)";
1480         case SIG_FEATDMF_TA:
1481                 return "Feature Groud D (MF) Tandem Access";
1482         case SIG_FEATB:
1483                 return "Feature Group B (MF)";
1484         case SIG_E911:
1485                 return "E911 (MF)";
1486         case SIG_FGC_CAMA:
1487                 return "FGC/CAMA (Dialpulse)";
1488         case SIG_FGC_CAMAMF:
1489                 return "FGC/CAMA (MF)";
1490         case SIG_FXSLS:
1491                 return "FXS Loopstart";
1492         case SIG_FXSGS:
1493                 return "FXS Groundstart";
1494         case SIG_FXSKS:
1495                 return "FXS Kewlstart";
1496         case SIG_FXOLS:
1497                 return "FXO Loopstart";
1498         case SIG_FXOGS:
1499                 return "FXO Groundstart";
1500         case SIG_FXOKS:
1501                 return "FXO Kewlstart";
1502         case SIG_PRI:
1503                 return "ISDN PRI";
1504         case SIG_BRI:
1505                 return "ISDN BRI Point to Point";
1506         case SIG_BRI_PTMP:
1507                 return "ISDN BRI Point to MultiPoint";
1508         case SIG_SS7:
1509                 return "SS7";
1510         case SIG_SF:
1511                 return "SF (Tone) Immediate";
1512         case SIG_SFWINK:
1513                 return "SF (Tone) Wink";
1514         case SIG_SF_FEATD:
1515                 return "SF (Tone) with Feature Group D (DTMF)";
1516         case SIG_SF_FEATDMF:
1517                 return "SF (Tone) with Feature Group D (MF)";
1518         case SIG_SF_FEATB:
1519                 return "SF (Tone) with Feature Group B (MF)";
1520         case SIG_GR303FXOKS:
1521                 return "GR-303 with FXOKS";
1522         case SIG_GR303FXSKS:
1523                 return "GR-303 with FXSKS";
1524         case 0:
1525                 return "Pseudo";
1526         default:
1527                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
1528                 return buf;
1529         }
1530 }
1531
1532 #define sig2str dahdi_sig2str
1533
1534 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
1535 {
1536         /* If the conference already exists, and we're already in it
1537            don't bother doing anything */
1538         struct dahdi_confinfo zi;
1539         
1540         memset(&zi, 0, sizeof(zi));
1541         zi.chan = 0;
1542
1543         if (slavechannel > 0) {
1544                 /* If we have only one slave, do a digital mon */
1545                 zi.confmode = DAHDI_CONF_DIGITALMON;
1546                 zi.confno = slavechannel;
1547         } else {
1548                 if (!idx) {
1549                         /* Real-side and pseudo-side both participate in conference */
1550                         zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
1551                                 DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
1552                 } else
1553                         zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
1554                 zi.confno = p->confno;
1555         }
1556         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
1557                 return 0;
1558         if (c->dfd < 0)
1559                 return 0;
1560         if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
1561                 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
1562                 return -1;
1563         }
1564         if (slavechannel < 1) {
1565                 p->confno = zi.confno;
1566         }
1567         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1568         ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
1569         return 0;
1570 }
1571
1572 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
1573 {
1574         /* If they're listening to our channel, they're ours */ 
1575         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
1576                 return 1;
1577         /* If they're a talker on our (allocated) conference, they're ours */
1578         if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
1579                 return 1;
1580         return 0;
1581 }
1582
1583 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
1584 {
1585         struct dahdi_confinfo zi;
1586         if (/* Can't delete if there's no dfd */
1587                 (c->dfd < 0) ||
1588                 /* Don't delete from the conference if it's not our conference */
1589                 !isourconf(p, c)
1590                 /* Don't delete if we don't think it's conferenced at all (implied) */
1591                 ) return 0;
1592         memset(&zi, 0, sizeof(zi));
1593         zi.chan = 0;
1594         zi.confno = 0;
1595         zi.confmode = 0;
1596         if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
1597                 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
1598                 return -1;
1599         }
1600         ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
1601         memcpy(&c->curconf, &zi, sizeof(c->curconf));
1602         return 0;
1603 }
1604
1605 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
1606 {
1607         int x;
1608         int useslavenative;
1609         struct dahdi_pvt *slave = NULL;
1610         /* Start out optimistic */
1611         useslavenative = 1;
1612         /* Update conference state in a stateless fashion */
1613         for (x = 0; x < 3; x++) {
1614                 /* Any three-way calling makes slave native mode *definitely* out
1615                    of the question */
1616                 if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
1617                         useslavenative = 0;
1618         }
1619         /* If we don't have any 3-way calls, check to see if we have
1620            precisely one slave */
1621         if (useslavenative) {
1622                 for (x = 0; x < MAX_SLAVES; x++) {
1623                         if (p->slaves[x]) {
1624                                 if (slave) {
1625                                         /* Whoops already have a slave!  No 
1626                                            slave native and stop right away */
1627                                         slave = NULL;
1628                                         useslavenative = 0;
1629                                         break;
1630                                 } else {
1631                                         /* We have one slave so far */
1632                                         slave = p->slaves[x];
1633                                 }
1634                         }
1635                 }
1636         }
1637         /* If no slave, slave native definitely out */
1638         if (!slave)
1639                 useslavenative = 0;
1640         else if (slave->law != p->law) {
1641                 useslavenative = 0;
1642                 slave = NULL;
1643         }
1644         if (out)
1645                 *out = slave;
1646         return useslavenative;
1647 }
1648
1649 static int reset_conf(struct dahdi_pvt *p)
1650 {
1651         struct dahdi_confinfo zi;
1652         memset(&zi, 0, sizeof(zi));
1653         p->confno = -1;
1654         memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
1655         if (p->subs[SUB_REAL].dfd > -1) {
1656                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
1657                         ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
1658         }
1659         return 0;
1660 }
1661
1662 static int update_conf(struct dahdi_pvt *p)
1663 {
1664         int needconf = 0;
1665         int x;
1666         int useslavenative;
1667         struct dahdi_pvt *slave = NULL;
1668
1669         useslavenative = isslavenative(p, &slave);
1670         /* Start with the obvious, general stuff */
1671         for (x = 0; x < 3; x++) {
1672                 /* Look for three way calls */
1673                 if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
1674                         conf_add(p, &p->subs[x], x, 0);
1675                         needconf++;
1676                 } else {
1677                         conf_del(p, &p->subs[x], x);
1678                 }
1679         }
1680         /* If we have a slave, add him to our conference now. or DAX
1681            if this is slave native */
1682         for (x = 0; x < MAX_SLAVES; x++) {
1683                 if (p->slaves[x]) {
1684                         if (useslavenative)
1685                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
1686                         else {
1687                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
1688                                 needconf++;
1689                         }
1690                 }
1691         }
1692         /* If we're supposed to be in there, do so now */
1693         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
1694                 if (useslavenative)
1695                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
1696                 else {
1697                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
1698                         needconf++;
1699                 }
1700         }
1701         /* If we have a master, add ourselves to his conference */
1702         if (p->master) {
1703                 if (isslavenative(p->master, NULL)) {
1704                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
1705                 } else {
1706                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
1707                 }
1708         }
1709         if (!needconf) {
1710                 /* Nobody is left (or should be left) in our conference.
1711                    Kill it. */
1712                 p->confno = -1;
1713         }
1714         ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
1715         return 0;
1716 }
1717
1718 static void dahdi_enable_ec(struct dahdi_pvt *p)
1719 {
1720         int x;
1721         int res;
1722         if (!p)
1723                 return;
1724         if (p->echocanon) {
1725                 ast_debug(1, "Echo cancellation already on\n");
1726                 return;
1727         }
1728         if (p->digital) {
1729                 ast_debug(1, "Echo cancellation isn't required on digital connection\n");
1730                 return;
1731         }
1732         if (p->echocancel.head.tap_length) {
1733                 if ((p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP) || (p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
1734                         x = 1;
1735                         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
1736                         if (res)
1737                                 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
1738                 }
1739                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
1740                 if (res)  {
1741                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
1742                 } else {
1743                         p->echocanon = 1;
1744                         ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
1745                 }
1746         } else
1747                 ast_debug(1, "No echo cancellation requested\n");
1748 }
1749
1750 static void dahdi_train_ec(struct dahdi_pvt *p)
1751 {
1752         int x;
1753         int res;
1754         
1755         if (p && p->echocanon && p->echotraining) {
1756                 x = p->echotraining;
1757                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
1758                 if (res)
1759                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
1760                 else
1761                         ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
1762         } else {
1763                 ast_debug(1, "No echo training requested\n");
1764         }
1765 }
1766
1767 static void dahdi_disable_ec(struct dahdi_pvt *p)
1768 {
1769         int res;
1770
1771         if (p->echocanon) {
1772                 struct dahdi_echocanparams ecp = { .tap_length = 0 };
1773
1774                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
1775
1776                 if (res)
1777                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
1778                 else
1779                         ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
1780         }
1781
1782         p->echocanon = 0;
1783 }
1784
1785 static void fill_txgain(struct dahdi_gains *g, float gain, int law)
1786 {
1787         int j;
1788         int k;
1789         float linear_gain = pow(10.0, gain / 20.0);
1790
1791         switch (law) {
1792         case DAHDI_LAW_ALAW:
1793                 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
1794                         if (gain) {
1795                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1796                                 if (k > 32767) k = 32767;
1797                                 if (k < -32767) k = -32767;
1798                                 g->txgain[j] = AST_LIN2A(k);
1799                         } else {
1800                                 g->txgain[j] = j;
1801                         }
1802                 }
1803                 break;
1804         case DAHDI_LAW_MULAW:
1805                 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
1806                         if (gain) {
1807                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1808                                 if (k > 32767) k = 32767;
1809                                 if (k < -32767) k = -32767;
1810                                 g->txgain[j] = AST_LIN2MU(k);
1811                         } else {
1812                                 g->txgain[j] = j;
1813                         }
1814                 }
1815                 break;
1816         }
1817 }
1818
1819 static void fill_rxgain(struct dahdi_gains *g, float gain, int law)
1820 {
1821         int j;
1822         int k;
1823         float linear_gain = pow(10.0, gain / 20.0);
1824
1825         switch (law) {
1826         case DAHDI_LAW_ALAW:
1827                 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
1828                         if (gain) {
1829                                 k = (int) (((float) AST_ALAW(j)) * linear_gain);
1830                                 if (k > 32767) k = 32767;
1831                                 if (k < -32767) k = -32767;
1832                                 g->rxgain[j] = AST_LIN2A(k);
1833                         } else {
1834                                 g->rxgain[j] = j;
1835                         }
1836                 }
1837                 break;
1838         case DAHDI_LAW_MULAW:
1839                 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
1840                         if (gain) {
1841                                 k = (int) (((float) AST_MULAW(j)) * linear_gain);
1842                                 if (k > 32767) k = 32767;
1843                                 if (k < -32767) k = -32767;
1844                                 g->rxgain[j] = AST_LIN2MU(k);
1845                         } else {
1846                                 g->rxgain[j] = j;
1847                         }
1848                 }
1849                 break;
1850         }
1851 }
1852
1853 static int set_actual_txgain(int fd, int chan, float gain, int law)
1854 {
1855         struct dahdi_gains g;
1856         int res;
1857
1858         memset(&g, 0, sizeof(g));
1859         g.chan = chan;
1860         res = ioctl(fd, DAHDI_GETGAINS, &g);
1861         if (res) {
1862                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
1863                 return res;
1864         }
1865
1866         fill_txgain(&g, gain, law);
1867
1868         return ioctl(fd, DAHDI_SETGAINS, &g);
1869 }
1870
1871 static int set_actual_rxgain(int fd, int chan, float gain, int law)
1872 {
1873         struct dahdi_gains g;
1874         int res;
1875
1876         memset(&g, 0, sizeof(g));
1877         g.chan = chan;
1878         res = ioctl(fd, DAHDI_GETGAINS, &g);
1879         if (res) {
1880                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
1881                 return res;
1882         }
1883
1884         fill_rxgain(&g, gain, law);
1885
1886         return ioctl(fd, DAHDI_SETGAINS, &g);
1887 }
1888
1889 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
1890 {
1891         return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
1892 }
1893
1894 static int bump_gains(struct dahdi_pvt *p)
1895 {
1896         int res;
1897
1898         /* Bump receive gain by value stored in cid_rxgain */
1899         res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain + p->cid_rxgain, p->txgain, p->law);
1900         if (res) {
1901                 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
1902                 return -1;
1903         }
1904
1905         return 0;
1906 }
1907
1908 static int restore_gains(struct dahdi_pvt *p)
1909 {
1910         int res;
1911
1912         res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
1913         if (res) {
1914                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
1915                 return -1;
1916         }
1917
1918         return 0;
1919 }
1920
1921 static inline int dahdi_set_hook(int fd, int hs)
1922 {
1923         int x, res;
1924
1925         x = hs;
1926         res = ioctl(fd, DAHDI_HOOK, &x);
1927
1928         if (res < 0) {
1929                 if (errno == EINPROGRESS)
1930                         return 0;
1931                 ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
1932                 /* will expectedly fail if phone is off hook during operation, such as during a restart */
1933         }
1934
1935         return res;
1936 }
1937
1938 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
1939 {
1940         int x, y, res;
1941         x = muted;
1942         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
1943                 y = 1;
1944                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
1945                 if (res)
1946                         ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n", p->channel, strerror(errno));
1947         }
1948         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
1949         if (res < 0)
1950                 ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
1951         return res;
1952 }
1953
1954 static int save_conference(struct dahdi_pvt *p)
1955 {
1956         struct dahdi_confinfo c;
1957         int res;
1958         if (p->saveconf.confmode) {
1959                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
1960                 return -1;
1961         }
1962         p->saveconf.chan = 0;
1963         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
1964         if (res) {
1965                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
1966                 p->saveconf.confmode = 0;
1967                 return -1;
1968         }
1969         c.chan = 0;
1970         c.confno = 0;
1971         c.confmode = DAHDI_CONF_NORMAL;
1972         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
1973         if (res) {
1974                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
1975                 return -1;
1976         }
1977         ast_debug(1, "Disabled conferencing\n");
1978         return 0;
1979 }
1980
1981 /*!
1982  * \brief Send MWI state change
1983  *
1984  * \arg mailbox_full This is the mailbox associated with the FXO line that the
1985  *      MWI state has changed on.
1986  * \arg thereornot This argument should simply be set to 1 or 0, to indicate
1987  *      whether there are messages waiting or not.
1988  *
1989  *  \return nothing
1990  *
1991  * This function does two things:
1992  *
1993  * 1) It generates an internal Asterisk event notifying any other module that
1994  *    cares about MWI that the state of a mailbox has changed.
1995  *
1996  * 2) It runs the script specified by the mwimonitornotify option to allow
1997  *    some custom handling of the state change.
1998  */
1999 static void notify_message(char *mailbox_full, int thereornot)
2000 {
2001         char s[sizeof(mwimonitornotify) + 80];
2002         struct ast_event *event;
2003         char *mailbox, *context;
2004
2005         /* Strip off @default */
2006         context = mailbox = ast_strdupa(mailbox_full);
2007         strsep(&context, "@");
2008         if (ast_strlen_zero(context))
2009                 context = "default";
2010
2011         if (!(event = ast_event_new(AST_EVENT_MWI,
2012                         AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
2013                         AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
2014                         AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
2015                         AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
2016                         AST_EVENT_IE_END))) {
2017                 return;
2018         }
2019
2020         ast_event_queue_and_cache(event,
2021                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR,
2022                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR,
2023                 AST_EVENT_IE_END);
2024
2025         if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
2026                 snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
2027                 ast_safe_system(s);
2028         }
2029 }
2030
2031 static int restore_conference(struct dahdi_pvt *p)
2032 {
2033         int res;
2034         if (p->saveconf.confmode) {
2035                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
2036                 p->saveconf.confmode = 0;
2037                 if (res) {
2038                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
2039                         return -1;
2040                 }
2041         }
2042         ast_debug(1, "Restored conferencing\n");
2043         return 0;
2044 }
2045
2046 static int send_callerid(struct dahdi_pvt *p);
2047
2048 static int send_cwcidspill(struct dahdi_pvt *p)
2049 {
2050         p->callwaitcas = 0;
2051         p->cidcwexpire = 0;
2052         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
2053                 return -1;
2054         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
2055         /* Make sure we account for the end */
2056         p->cidlen += READ_SIZE * 4;
2057         p->cidpos = 0;
2058         send_callerid(p);
2059         ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
2060         return 0;
2061 }
2062
2063 static int has_voicemail(struct dahdi_pvt *p)
2064 {
2065         int new_msgs;
2066         struct ast_event *event;
2067         char *mailbox, *context;
2068
2069         mailbox = context = ast_strdupa(p->mailbox);
2070         strsep(&context, "@");
2071         if (ast_strlen_zero(context))
2072                 context = "default";
2073
2074         event = ast_event_get_cached(AST_EVENT_MWI,
2075                 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
2076                 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
2077                 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_EXISTS,
2078                 AST_EVENT_IE_END);
2079
2080         if (event) {
2081                 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
2082                 ast_event_destroy(event);
2083         } else
2084                 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
2085
2086         return new_msgs;
2087 }
2088
2089 static int send_callerid(struct dahdi_pvt *p)
2090 {
2091         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
2092         int res;
2093         /* Take out of linear mode if necessary */
2094         if (p->subs[SUB_REAL].linear) {
2095                 p->subs[SUB_REAL].linear = 0;
2096                 dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
2097         }
2098         while (p->cidpos < p->cidlen) {
2099                 res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
2100                 if (res < 0) {
2101                         if (errno == EAGAIN)
2102                                 return 0;
2103                         else {
2104                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
2105                                 return -1;
2106                         }
2107                 }
2108                 if (!res)
2109                         return 0;
2110                 p->cidpos += res;
2111         }
2112         ast_free(p->cidspill);
2113         p->cidspill = NULL;
2114         if (p->callwaitcas) {
2115                 /* Wait for CID/CW to expire */
2116                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
2117         } else
2118                 restore_conference(p);
2119         return 0;
2120 }
2121
2122 static int dahdi_callwait(struct ast_channel *ast)
2123 {
2124         struct dahdi_pvt *p = ast->tech_pvt;
2125         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
2126         if (p->cidspill) {
2127                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
2128                 ast_free(p->cidspill);
2129         }
2130         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
2131                 return -1;
2132         save_conference(p);
2133         /* Silence */
2134         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
2135         if (!p->callwaitrings && p->callwaitingcallerid) {
2136                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
2137                 p->callwaitcas = 1;
2138                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
2139         } else {
2140                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
2141                 p->callwaitcas = 0;
2142                 p->cidlen = 2400 + READ_SIZE * 4;
2143         }
2144         p->cidpos = 0;
2145         send_callerid(p);
2146         
2147         return 0;
2148 }
2149
2150 #ifdef HAVE_SS7
2151 static unsigned char cid_pres2ss7pres(int cid_pres)
2152 {
2153          return (cid_pres >> 5) & 0x03;
2154 }
2155
2156 static unsigned char cid_pres2ss7screen(int cid_pres)
2157 {
2158         return cid_pres & 0x03;
2159 }
2160 #endif
2161
2162 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
2163 {
2164         struct dahdi_pvt *p = ast->tech_pvt;
2165         int x, res, idx,mysig;
2166         char *c, *n, *l;
2167 #ifdef HAVE_PRI
2168         char *s = NULL;
2169 #endif
2170         char dest[256]; /* must be same length as p->dialdest */
2171         ast_mutex_lock(&p->lock);
2172         ast_copy_string(dest, rdest, sizeof(dest));
2173         ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
2174         if ((ast->_state == AST_STATE_BUSY)) {
2175                 p->subs[SUB_REAL].needbusy = 1;
2176                 ast_mutex_unlock(&p->lock);
2177                 return 0;
2178         }
2179         if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
2180                 ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
2181                 ast_mutex_unlock(&p->lock);
2182                 return -1;
2183         }
2184         p->dialednone = 0;
2185         if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
2186         {
2187                 /* Special pseudo -- automatically up */
2188                 ast_setstate(ast, AST_STATE_UP); 
2189                 ast_mutex_unlock(&p->lock);
2190                 return 0;
2191         }
2192         x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
2193         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
2194         if (res)
2195                 ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
2196         p->outgoing = 1;
2197
2198         set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
2199
2200         mysig = p->sig;
2201         if (p->outsigmod > -1)
2202                 mysig = p->outsigmod;
2203
2204         switch (mysig) {
2205         case SIG_FXOLS:
2206         case SIG_FXOGS:
2207         case SIG_FXOKS:
2208                 if (p->owner == ast) {
2209                         /* Normal ring, on hook */
2210                         
2211                         /* Don't send audio while on hook, until the call is answered */
2212                         p->dialing = 1;
2213                         if (p->use_callerid) {
2214                                 /* Generate the Caller-ID spill if desired */
2215                                 if (p->cidspill) {
2216                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
2217                                         ast_free(p->cidspill);
2218                                 }
2219                                 p->callwaitcas = 0;
2220                                 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
2221                                         p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
2222                                         p->cidpos = 0;
2223                                         send_callerid(p);
2224                                 }
2225                         }
2226                         /* Choose proper cadence */
2227                         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
2228                                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
2229                                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast->name, strerror(errno));
2230                                 p->cidrings = cidrings[p->distinctivering - 1];
2231                         } else {
2232                                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
2233                                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast->name, strerror(errno));
2234                                 p->cidrings = p->sendcalleridafter;
2235                         }
2236
2237                         /* nick@dccinc.com 4/3/03 mods to allow for deferred dialing */
2238                         c = strchr(dest, '/');
2239                         if (c)
2240                                 c++;
2241                         if (c && (strlen(c) < p->stripmsd)) {
2242                                 ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2243                                 c = NULL;
2244                         }
2245                         if (c) {
2246                                 p->dop.op = DAHDI_DIAL_OP_REPLACE;
2247                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "Tw%s", c);
2248                                 ast_debug(1, "FXO: setup deferred dialstring: %s\n", c);
2249                         } else {
2250                                 p->dop.dialstr[0] = '\0';
2251                         }
2252                         x = DAHDI_RING;
2253                         if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x) && (errno != EINPROGRESS)) {
2254                                 ast_log(LOG_WARNING, "Unable to ring phone: %s\n", strerror(errno));
2255                                 ast_mutex_unlock(&p->lock);
2256                                 return -1;
2257                         }
2258                         p->dialing = 1;
2259                 } else {
2260                         /* Call waiting call */
2261                         p->callwaitrings = 0;
2262                         if (ast->cid.cid_num)
2263                                 ast_copy_string(p->callwait_num, ast->cid.cid_num, sizeof(p->callwait_num));
2264                         else
2265                                 p->callwait_num[0] = '\0';
2266                         if (ast->cid.cid_name)
2267                                 ast_copy_string(p->callwait_name, ast->cid.cid_name, sizeof(p->callwait_name));
2268                         else
2269                                 p->callwait_name[0] = '\0';
2270                         /* Call waiting tone instead */
2271                         if (dahdi_callwait(ast)) {
2272                                 ast_mutex_unlock(&p->lock);
2273                                 return -1;
2274                         }
2275                         /* Make ring-back */
2276                         if (tone_zone_play_tone(p->subs[SUB_CALLWAIT].dfd, DAHDI_TONE_RINGTONE))
2277                                 ast_log(LOG_WARNING, "Unable to generate call-wait ring-back on channel %s\n", ast->name);
2278                                 
2279                 }
2280                 n = ast->cid.cid_name;
2281                 l = ast->cid.cid_num;
2282                 if (l)
2283                         ast_copy_string(p->lastcid_num, l, sizeof(p->lastcid_num));
2284                 else
2285                         p->lastcid_num[0] = '\0';
2286                 if (n)
2287                         ast_copy_string(p->lastcid_name, n, sizeof(p->lastcid_name));
2288                 else
2289                         p->lastcid_name[0] = '\0';
2290                 ast_setstate(ast, AST_STATE_RINGING);
2291                 idx = dahdi_get_index(ast, p, 0);
2292                 if (idx > -1) {
2293                         p->subs[idx].needringing = 1;
2294                 }
2295                 break;
2296         case SIG_FXSLS:
2297         case SIG_FXSGS:
2298         case SIG_FXSKS:
2299         case SIG_EMWINK:
2300         case SIG_EM:
2301         case SIG_EM_E1:
2302         case SIG_FEATD:
2303         case SIG_FEATDMF:
2304         case SIG_E911:
2305         case SIG_FGC_CAMA:
2306         case SIG_FGC_CAMAMF:
2307         case SIG_FEATB:
2308         case SIG_SFWINK:
2309         case SIG_SF:
2310         case SIG_SF_FEATD:
2311         case SIG_SF_FEATDMF:
2312         case SIG_FEATDMF_TA:
2313         case SIG_SF_FEATB:
2314                 c = strchr(dest, '/');
2315                 if (c)
2316                         c++;
2317                 else
2318                         c = "";
2319                 if (strlen(c) < p->stripmsd) {
2320                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2321                         ast_mutex_unlock(&p->lock);
2322                         return -1;
2323                 }
2324 #ifdef HAVE_PRI
2325                 /* Start the trunk, if not GR-303 */
2326                 if (!p->pri) {
2327 #endif
2328                         x = DAHDI_START;
2329                         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
2330                         if (res < 0) {
2331                                 if (errno != EINPROGRESS) {
2332                                         ast_log(LOG_WARNING, "Unable to start channel: %s\n", strerror(errno));
2333                                         ast_mutex_unlock(&p->lock);
2334                                         return -1;
2335                                 }
2336                         }
2337 #ifdef HAVE_PRI
2338                 }
2339 #endif
2340                 ast_debug(1, "Dialing '%s'\n", c);
2341                 p->dop.op = DAHDI_DIAL_OP_REPLACE;
2342
2343                 c += p->stripmsd;
2344
2345                 switch (mysig) {
2346                 case SIG_FEATD:
2347                         l = ast->cid.cid_num;
2348                         if (l) 
2349                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T*%s*%s*", l, c);
2350                         else
2351                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T**%s*", c);
2352                         break;
2353                 case SIG_FEATDMF:
2354                         l = ast->cid.cid_num;
2355                         if (l) 
2356                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*00%s#*%s#", l, c);
2357                         else
2358                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*02#*%s#", c);
2359                         break;
2360                 case SIG_FEATDMF_TA:
2361                 {
2362                         const char *cic, *ozz;
2363
2364                         /* If you have to go through a Tandem Access point you need to use this */
2365                         ozz = pbx_builtin_getvar_helper(p->owner, "FEATDMF_OZZ");
2366                         if (!ozz)
2367                                 ozz = defaultozz;
2368                         cic = pbx_builtin_getvar_helper(p->owner, "FEATDMF_CIC");
2369                         if (!cic)
2370                                 cic = defaultcic;
2371                         if (!ozz || !cic) {
2372                                 ast_log(LOG_WARNING, "Unable to dial channel of type feature group D MF tandem access without CIC or OZZ set\n");
2373                                 ast_mutex_unlock(&p->lock);
2374                                 return -1;
2375                         }
2376                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s%s#", ozz, cic);
2377                         snprintf(p->finaldial, sizeof(p->finaldial), "M*%s#", c);
2378                         p->whichwink = 0;
2379                 }
2380                         break;
2381                 case SIG_E911:
2382                         ast_copy_string(p->dop.dialstr, "M*911#", sizeof(p->dop.dialstr));
2383                         break;
2384                 case SIG_FGC_CAMA:
2385                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%s", c);
2386                         break;
2387                 case SIG_FGC_CAMAMF:
2388                 case SIG_FEATB:
2389                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "M*%s#", c);
2390                         break;
2391                 default:
2392                         if (p->pulse)
2393                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "P%sw", c);
2394                         else
2395                                 snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%sw", c);
2396                         break;
2397                 }
2398
2399                 if (p->echotraining && (strlen(p->dop.dialstr) > 4)) {
2400                         memset(p->echorest, 'w', sizeof(p->echorest) - 1);
2401                         strcpy(p->echorest + (p->echotraining / 400) + 1, p->dop.dialstr + strlen(p->dop.dialstr) - 2);
2402                         p->echorest[sizeof(p->echorest) - 1] = '\0';
2403                         p->echobreak = 1;
2404                         p->dop.dialstr[strlen(p->dop.dialstr)-2] = '\0';
2405                 } else
2406                         p->echobreak = 0;
2407                 if (!res) {
2408                         if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_DIAL, &p->dop)) {
2409                                 int saveerr = errno;
2410
2411                                 x = DAHDI_ONHOOK;
2412                                 ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
2413                                 ast_log(LOG_WARNING, "Dialing failed on channel %d: %s\n", p->channel, strerror(saveerr));
2414                                 ast_mutex_unlock(&p->lock);
2415                                 return -1;
2416                         }
2417                 } else
2418                         ast_debug(1, "Deferring dialing...\n");
2419
2420                 p->dialing = 1;
2421                 if (ast_strlen_zero(c))
2422                         p->dialednone = 1;
2423                 ast_setstate(ast, AST_STATE_DIALING);
2424                 break;
2425         case 0:
2426                 /* Special pseudo -- automatically up*/
2427                 ast_setstate(ast, AST_STATE_UP);
2428                 break;          
2429         case SIG_PRI:
2430         case SIG_BRI:
2431         case SIG_BRI_PTMP:
2432         case SIG_SS7:
2433                 /* We'll get it in a moment -- but use dialdest to store pre-setup_ack digits */
2434                 p->dialdest[0] = '\0';
2435                 break;
2436         default:
2437                 ast_debug(1, "not yet implemented\n");
2438                 ast_mutex_unlock(&p->lock);
2439                 return -1;
2440         }
2441 #ifdef HAVE_SS7
2442         if (p->ss7) {
2443                 char ss7_called_nai;
2444                 int called_nai_strip;
2445                 char ss7_calling_nai;
2446                 int calling_nai_strip;
2447                 const char *charge_str = NULL;
2448                 const char *gen_address = NULL;
2449                 const char *gen_digits = NULL;
2450                 const char *gen_dig_type = NULL;
2451                 const char *gen_dig_scheme = NULL;
2452                 const char *gen_name = NULL;
2453                 const char *jip_digits = NULL;
2454                 const char *lspi_ident = NULL;
2455                 const char *rlt_flag = NULL;
2456                 const char *call_ref_id = NULL;
2457                 const char *call_ref_pc = NULL;
2458                 const char *send_far = NULL;
2459
2460                 c = strchr(dest, '/');
2461                 if (c)
2462                         c++;
2463                 else
2464                         c = dest;
2465
2466                 if (!p->hidecallerid) {
2467                         l = ast->cid.cid_num;
2468                 } else {
2469                         l = NULL;
2470                 }
2471
2472                 if (ss7_grab(p, p->ss7)) {
2473                         ast_log(LOG_WARNING, "Failed to grab SS7!\n");
2474                         ast_mutex_unlock(&p->lock);
2475                         return -1;
2476                 }
2477                 p->digital = IS_DIGITAL(ast->transfercapability);
2478                 p->ss7call = isup_new_call(p->ss7->ss7);
2479
2480                 if (!p->ss7call) {
2481                         ss7_rel(p->ss7);
2482                         ast_mutex_unlock(&p->lock);
2483                         ast_log(LOG_ERROR, "Unable to allocate new SS7 call!\n");
2484                         return -1;
2485                 }
2486
2487                 called_nai_strip = 0;
2488                 ss7_called_nai = p->ss7->called_nai;
2489                 if (ss7_called_nai == SS7_NAI_DYNAMIC) { /* compute dynamically */
2490                         if (strncmp(c + p->stripmsd, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
2491                                 called_nai_strip = strlen(p->ss7->internationalprefix);
2492                                 ss7_called_nai = SS7_NAI_INTERNATIONAL;
2493                         } else if (strncmp(c + p->stripmsd, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
2494                                 called_nai_strip = strlen(p->ss7->nationalprefix);
2495                                 ss7_called_nai = SS7_NAI_NATIONAL;
2496                         } else {
2497                                 ss7_called_nai = SS7_NAI_SUBSCRIBER;
2498                         }
2499                 }
2500                 isup_set_called(p->ss7call, c + p->stripmsd + called_nai_strip, ss7_called_nai, p->ss7->ss7);
2501
2502                 calling_nai_strip = 0;
2503                 ss7_calling_nai = p->ss7->calling_nai;
2504                 if ((l != NULL) && (ss7_calling_nai == SS7_NAI_DYNAMIC)) { /* compute dynamically */
2505                         if (strncmp(l, p->ss7->internationalprefix, strlen(p->ss7->internationalprefix)) == 0) {
2506                                 calling_nai_strip = strlen(p->ss7->internationalprefix);
2507                                 ss7_calling_nai = SS7_NAI_INTERNATIONAL;
2508                         } else if (strncmp(l, p->ss7->nationalprefix, strlen(p->ss7->nationalprefix)) == 0) {
2509                                 calling_nai_strip = strlen(p->ss7->nationalprefix);
2510                                 ss7_calling_nai = SS7_NAI_NATIONAL;
2511                         } else {
2512                                 ss7_calling_nai = SS7_NAI_SUBSCRIBER;
2513                         }
2514                 }
2515                 isup_set_calling(p->ss7call, l ? (l + calling_nai_strip) : NULL, ss7_calling_nai,
2516                         p->use_callingpres ? cid_pres2ss7pres(ast->cid.cid_pres) : (l ? SS7_PRESENTATION_ALLOWED : SS7_PRESENTATION_RESTRICTED),
2517                         p->use_callingpres ? cid_pres2ss7screen(ast->cid.cid_pres) : SS7_SCREENING_USER_PROVIDED );
2518
2519                 isup_set_oli(p->ss7call, ast->cid.cid_ani2);
2520                 isup_init_call(p->ss7->ss7, p->ss7call, p->cic, p->dpc);
2521
2522                 ast_channel_lock(ast);
2523                 /* Set the charge number if it is set */
2524                 charge_str = pbx_builtin_getvar_helper(ast, "SS7_CHARGE_NUMBER");
2525                 if (charge_str)
2526                         isup_set_charge(p->ss7call, charge_str, SS7_ANI_CALLING_PARTY_SUB_NUMBER, 0x10);
2527                 
2528                 gen_address = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_ADDRESS");
2529                 if (gen_address)
2530                         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 */
2531                 
2532                 gen_digits = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGITS");
2533                 gen_dig_type = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGTYPE");
2534                 gen_dig_scheme = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_DIGSCHEME");
2535                 if (gen_digits)
2536                         isup_set_gen_digits(p->ss7call, gen_digits, atoi(gen_dig_type), atoi(gen_dig_scheme)); 
2537                 
2538                 gen_name = pbx_builtin_getvar_helper(ast, "SS7_GENERIC_NAME");
2539                 if (gen_name)
2540                         isup_set_generic_name(p->ss7call, gen_name, GEN_NAME_TYPE_CALLING_NAME, GEN_NAME_AVAIL_AVAILABLE, GEN_NAME_PRES_ALLOWED);
2541
2542                 jip_digits = pbx_builtin_getvar_helper(ast, "SS7_JIP");
2543                 if (jip_digits)
2544                         isup_set_jip_digits(p->ss7call, jip_digits);
2545                 
2546                 lspi_ident = pbx_builtin_getvar_helper(ast, "SS7_LSPI_IDENT");
2547                 if (lspi_ident)
2548                         isup_set_lspi(p->ss7call, lspi_ident, 0x18, 0x7, 0x00); 
2549                 
2550                 rlt_flag = pbx_builtin_getvar_helper(ast, "SS7_RLT_ON");
2551                 if ((rlt_flag) && ((strncmp("NO", rlt_flag, strlen(rlt_flag))) != 0 )) {
2552                         isup_set_lspi(p->ss7call, rlt_flag, 0x18, 0x7, 0x00); /* Setting for Nortel DMS-250/500 */
2553                 }
2554                 
2555                 call_ref_id = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_IDENT");
2556                 call_ref_pc = pbx_builtin_getvar_helper(ast, "SS7_CALLREF_PC");
2557                 if (call_ref_id && call_ref_pc) {
2558                         isup_set_callref(p->ss7call, atoi(call_ref_id),
2559                                          call_ref_pc ? atoi(call_ref_pc) : 0);
2560                 }
2561                 
2562                 send_far = pbx_builtin_getvar_helper(ast, "SS7_SEND_FAR");
2563                 if ((send_far) && ((strncmp("NO", send_far, strlen(send_far))) != 0 ))
2564                         (isup_far(p->ss7->ss7, p->ss7call));
2565                 
2566                 ast_channel_unlock(ast);
2567
2568                 isup_iam(p->ss7->ss7, p->ss7call);
2569                 ast_setstate(ast, AST_STATE_DIALING);
2570                 ss7_rel(p->ss7);
2571         }
2572 #endif /* HAVE_SS7 */
2573 #ifdef HAVE_PRI
2574         if (p->pri) {
2575                 struct pri_sr *sr;
2576 #ifdef SUPPORT_USERUSER
2577                 const char *useruser;
2578 #endif
2579                 int pridialplan;
2580                 int dp_strip;
2581                 int prilocaldialplan;
2582                 int ldp_strip;
2583                 int exclusive;
2584                 const char *rr_str;
2585                 int redirect_reason;
2586
2587                 c = strchr(dest, '/');
2588                 if (c)
2589                         c++;
2590                 else
2591                         c = dest;
2592
2593                 l = NULL;
2594                 n = NULL;
2595
2596                 if (!p->hidecallerid) {
2597                         l = ast->cid.cid_num;
2598                         if (!p->hidecalleridname) {
2599                                 n = ast->cid.cid_name;
2600                         }
2601                 }
2602
2603                 if (strlen(c) < p->stripmsd) {
2604                         ast_log(LOG_WARNING, "Number '%s' is shorter than stripmsd (%d)\n", c, p->stripmsd);
2605                         ast_mutex_unlock(&p->lock);
2606                         return -1;
2607                 }
2608                 if (mysig != SIG_FXSKS) {
2609                         p->dop.op = DAHDI_DIAL_OP_REPLACE;
2610                         s = strchr(c + p->stripmsd, 'w');
2611                         if (s) {
2612                                 if (strlen(s) > 1)
2613                                         snprintf(p->dop.dialstr, sizeof(p->dop.dialstr), "T%s", s);
2614                                 else
2615                                         p->dop.dialstr[0] = '\0';
2616                                 *s = '\0';
2617                         } else {
2618                                 p->dop.dialstr[0] = '\0';
2619                         }
2620                 }
2621                 if (pri_grab(p, p->pri)) {
2622                         ast_log(LOG_WARNING, "Failed to grab PRI!\n");
2623                         ast_mutex_unlock(&p->lock);
2624                         return -1;
2625                 }
2626                 if (!(p->call = pri_new_call(p->pri->pri))) {
2627                         ast_log(LOG_WARNING, "Unable to create call on channel %d\n", p->channel);
2628                         pri_rel(p->pri);
2629                         ast_mutex_unlock(&p->lock);
2630                         return -1;
2631                 }
2632                 if (!(sr = pri_sr_new())) {
2633                         ast_log(LOG_WARNING, "Failed to allocate setup request channel %d\n", p->channel);
2634                         pri_rel(p->pri);
2635                         ast_mutex_unlock(&p->lock);
2636                 }
2637                 if (p->bearer || (mysig == SIG_FXSKS)) {
2638                         if (p->bearer) {
2639                                 ast_debug(1, "Oooh, I have a bearer on %d (%d:%d)\n", PVT_TO_CHANNEL(p->bearer), p->bearer->logicalspan, p->bearer->channel);
2640                                 p->bearer->call = p->call;
2641                         } else
2642                                 ast_debug(1, "I'm being setup with no bearer right now...\n");
2643
2644                         pri_set_crv(p->pri->pri, p->call, p->channel, 0);
2645                 }
2646                 p->digital = IS_DIGITAL(ast->transfercapability);
2647                 /* Add support for exclusive override */
2648                 if (p->priexclusive)
2649                         exclusive = 1;
2650                 else {
2651                 /* otherwise, traditional behavior */
2652                         if (p->pri->nodetype == PRI_NETWORK)
2653                                 exclusive = 0;
2654                         else
2655                                 exclusive = 1;
2656                 }
2657                 
2658                 pri_sr_set_channel(sr, p->bearer ? PVT_TO_CHANNEL(p->bearer) : PVT_TO_CHANNEL(p), exclusive, 1);
2659                 pri_sr_set_bearer(sr, p->digital ? PRI_TRANS_CAP_DIGITAL : ast->transfercapability, 
2660                                         (p->digital ? -1 : 
2661                                                 ((p->law == DAHDI_LAW_ALAW) ? PRI_LAYER_1_ALAW : PRI_LAYER_1_ULAW)));
2662                 if (p->pri->facilityenable)
2663                         pri_facility_enable(p->pri->pri);
2664
2665                 ast_verb(3, "Requested transfer capability: 0x%.2x - %s\n", ast->transfercapability, ast_transfercapability2str(ast->transfercapability));
2666                 dp_strip = 0;
2667                 pridialplan = p->pri->dialplan - 1;
2668                 if (pridialplan == -2 || pridialplan == -3) { /* compute dynamically */
2669                         if (strncmp(c + p->stripmsd, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2670                                 if (pridialplan == -2) {
2671                                         dp_strip = strlen(p->pri->internationalprefix);
2672                                 }
2673                                 pridialplan = PRI_INTERNATIONAL_ISDN;
2674                         } else if (strncmp(c + p->stripmsd, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2675                                 if (pridialplan == -2) {
2676                                         dp_strip = strlen(p->pri->nationalprefix);
2677                                 }
2678                                 pridialplan = PRI_NATIONAL_ISDN;
2679                         } else {
2680                                 pridialplan = PRI_LOCAL_ISDN;
2681                         }
2682                 }
2683                 while (c[p->stripmsd] > '9' && c[p->stripmsd] != '*' && c[p->stripmsd] != '#') {
2684                         switch (c[p->stripmsd]) {
2685                         case 'U':
2686                                 pridialplan = (PRI_TON_UNKNOWN << 4) | (pridialplan & 0xf);
2687                                 break;
2688                         case 'I':
2689                                 pridialplan = (PRI_TON_INTERNATIONAL << 4) | (pridialplan & 0xf);
2690                                 break;
2691                         case 'N':
2692                                 pridialplan = (PRI_TON_NATIONAL << 4) | (pridialplan & 0xf);
2693                                 break;
2694                         case 'L':
2695                                 pridialplan = (PRI_TON_NET_SPECIFIC << 4) | (pridialplan & 0xf);
2696                                 break;
2697                         case 'S':
2698                                 pridialplan = (PRI_TON_SUBSCRIBER << 4) | (pridialplan & 0xf);
2699                                 break;
2700                         case 'V':
2701                                 pridialplan = (PRI_TON_ABBREVIATED << 4) | (pridialplan & 0xf);
2702                                 break;
2703                         case 'R':
2704                                 pridialplan = (PRI_TON_RESERVED << 4) | (pridialplan & 0xf);
2705                                 break;
2706                         case 'u':
2707                                 pridialplan = PRI_NPI_UNKNOWN | (pridialplan & 0xf0);
2708                                 break;
2709                         case 'e':
2710                                 pridialplan = PRI_NPI_E163_E164 | (pridialplan & 0xf0);
2711                                 break;
2712                         case 'x':
2713                                 pridialplan = PRI_NPI_X121 | (pridialplan & 0xf0);
2714                                 break;
2715                         case 'f':
2716                                 pridialplan = PRI_NPI_F69 | (pridialplan & 0xf0);
2717                                 break;
2718                         case 'n':
2719                                 pridialplan = PRI_NPI_NATIONAL | (pridialplan & 0xf0);
2720                                 break;
2721                         case 'p':
2722                                 pridialplan = PRI_NPI_PRIVATE | (pridialplan & 0xf0);
2723                                 break;
2724                         case 'r':
2725                                 pridialplan = PRI_NPI_RESERVED | (pridialplan & 0xf0);
2726                                 break;
2727                         default:
2728                                 if (isalpha(*c))
2729                                         ast_log(LOG_WARNING, "Unrecognized pridialplan %s modifier: %c\n", *c > 'Z' ? "NPI" : "TON", *c);
2730                         }
2731                         c++;
2732                 }
2733                 pri_sr_set_called(sr, c + p->stripmsd + dp_strip, pridialplan, s ? 1 : 0);
2734
2735                 ldp_strip = 0;
2736                 prilocaldialplan = p->pri->localdialplan - 1;
2737                 if ((l != NULL) && (prilocaldialplan == -2 || prilocaldialplan == -3)) { /* compute dynamically */
2738                         if (strncmp(l, p->pri->internationalprefix, strlen(p->pri->internationalprefix)) == 0) {
2739                                 if (prilocaldialplan == -2) {
2740                                         ldp_strip = strlen(p->pri->internationalprefix);
2741                                 }
2742                                 prilocaldialplan = PRI_INTERNATIONAL_ISDN;
2743                         } else if (strncmp(l, p->pri->nationalprefix, strlen(p->pri->nationalprefix)) == 0) {
2744                                 if (prilocaldialplan == -2) {
2745                                         ldp_strip = strlen(p->pri->nationalprefix);
2746                                 }
2747                                 prilocaldialplan = PRI_NATIONAL_ISDN;
2748                         } else {
2749                                 prilocaldialplan = PRI_LOCAL_ISDN;
2750                         }
2751                 }
2752                 if (l != NULL) {
2753                         while (*l > '9' && *l != '*' && *l != '#') {
2754                                 switch (*l) {
2755                                 case 'U':
2756                                         prilocaldialplan = (PRI_TON_UNKNOWN << 4) | (prilocaldialplan & 0xf);
2757                                         break;
2758                                 case 'I':
2759                                         prilocaldialplan = (PRI_TON_INTERNATIONAL << 4) | (prilocaldialplan & 0xf);
2760                                         break;
2761                                 case 'N':
2762                                         prilocaldialplan = (PRI_TON_NATIONAL << 4) | (prilocaldialplan & 0xf);
2763                                         break;
2764                                 case 'L':
2765                                         prilocaldialplan = (PRI_TON_NET_SPECIFIC << 4) | (prilocaldialplan & 0xf);
2766                                         break;
2767                                 case 'S':
2768                                         prilocaldialplan = (PRI_TON_SUBSCRIBER << 4) | (prilocaldialplan & 0xf);
2769                                         break;
2770                                 case 'V':
2771                                         prilocaldialplan = (PRI_TON_ABBREVIATED << 4) | (prilocaldialplan & 0xf);
2772                                         break;
2773                                 case 'R':
2774                                         prilocaldialplan = (PRI_TON_RESERVED << 4) | (prilocaldialplan & 0xf);
2775                                         break;
2776                                 case 'u':
2777                                         prilocaldialplan = PRI_NPI_UNKNOWN | (prilocaldialplan & 0xf0);
2778                                         break;
2779                                 case 'e':
2780                                         prilocaldialplan = PRI_NPI_E163_E164 | (prilocaldialplan & 0xf0);
2781                                         break;
2782                                 case 'x':
2783                                         prilocaldialplan = PRI_NPI_X121 | (prilocaldialplan & 0xf0);
2784                                         break;
2785                                 case 'f':
2786                                         prilocaldialplan = PRI_NPI_F69 | (prilocaldialplan & 0xf0);
2787                                         break;
2788                                 case 'n':
2789                                         prilocaldialplan = PRI_NPI_NATIONAL | (prilocaldialplan & 0xf0);
2790                                         break;
2791                                 case 'p':
2792                                         prilocaldialplan = PRI_NPI_PRIVATE | (prilocaldialplan & 0xf0);
2793                                         break;
2794                                 case 'r':
2795                                         prilocaldialplan = PRI_NPI_RESERVED | (prilocaldialplan & 0xf0);
2796                                         break;
2797                                 default:
2798                                         if (isalpha(*l))
2799                                                 ast_log(LOG_WARNING, "Unrecognized prilocaldialplan %s modifier: %c\n", *c > 'Z' ? "NPI" : "TON", *c);
2800                                 }
2801                                 l++;
2802                         }
2803                 }
2804                 pri_sr_set_caller(sr, l ? (l + ldp_strip) : NULL, n, prilocaldialplan,
2805                         p->use_callingpres ? ast->cid.cid_pres : (l ? PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN : PRES_NUMBER_NOT_AVAILABLE));
2806                 if ((rr_str = pbx_builtin_getvar_helper(ast, "PRIREDIRECTREASON"))) {
2807                         if (!strcasecmp(rr_str, "UNKNOWN"))
2808                                 redirect_reason = 0;
2809                         else if (!strcasecmp(rr_str, "BUSY"))
2810                                 redirect_reason = 1;
2811                         else if (!strcasecmp(rr_str, "NO_REPLY"))
2812                                 redirect_reason = 2;
2813                         else if (!strcasecmp(rr_str, "UNCONDITIONAL"))
2814                                 redirect_reason = 15;
2815                         else
2816                                 redirect_reason = PRI_REDIR_UNCONDITIONAL;
2817                 } else
2818                         redirect_reason = PRI_REDIR_UNCONDITIONAL;
2819                 pri_sr_set_redirecting(sr, ast->cid.cid_rdnis, p->pri->localdialplan - 1, PRES_ALLOWED_USER_NUMBER_PASSED_SCREEN, redirect_reason);
2820
2821 #ifdef SUPPORT_USERUSER
2822                 /* User-user info */
2823                 useruser = pbx_builtin_getvar_helper(p->owner, "USERUSERINFO");
2824
2825                 if (useruser)
2826                         pri_sr_set_useruser(sr, useruser);
2827 #endif
2828
2829                 if (pri_setup(p->pri->pri, p->call, sr)) {
2830                         ast_log(LOG_WARNING, "Unable to setup call to %s (using %s)\n", 
2831                                 c + p->stripmsd + dp_strip, dialplan2str(p->pri->dialplan));
2832                         pri_rel(p->pri);
2833                         ast_mutex_unlock(&p->lock);
2834                         pri_sr_free(sr);
2835                         return -1;
2836                 }
2837                 pri_sr_free(sr);
2838                 ast_setstate(ast, AST_STATE_DIALING);
2839                 pri_rel(p->pri);
2840         }
2841 #endif          
2842         ast_mutex_unlock(&p->lock);
2843         return 0;
2844 }
2845
2846 static void destroy_dahdi_pvt(struct dahdi_pvt **pvt)
2847 {
2848         struct dahdi_pvt *p = *pvt;
2849         /* Remove channel from the list */
2850         if (p->prev)
2851                 p->prev->next = p->next;
2852         if (p->next)
2853                 p->next->prev = p->prev;
2854         if (p->use_smdi)
2855                 ast_smdi_interface_unref(p->smdi_iface);
2856         if (p->mwi_event_sub)
2857                 ast_event_unsubscribe(p->mwi_event_sub);
2858         if (p->vars)
2859                 ast_variables_destroy(p->vars);
2860         ast_mutex_destroy(&p->lock);
2861         dahdi_close_sub(p, SUB_REAL);
2862         if (p->owner)
2863                 p->owner->tech_pvt = NULL;
2864         free(p);
2865         *pvt = NULL;
2866 }
2867
2868 static int destroy_channel(struct dahdi_pvt *prev, struct dahdi_pvt *cur, int now)
2869 {
2870         int owned = 0;
2871         int i = 0;
2872
2873         if (!now) {
2874                 if (cur->owner) {
2875                         owned = 1;
2876                 }
2877
2878                 for (i = 0; i < 3; i++) {
2879                         if (cur->subs[i].owner) {
2880                                 owned = 1;
2881                         }
2882                 }
2883                 if (!owned) {
2884                         if (prev) {
2885                                 prev->next = cur->next;
2886                                 if (prev->next)
2887                                         prev->next->prev = prev;
2888                                 else
2889                                         ifend = prev;
2890                         } else {
2891                                 iflist = cur->next;
2892                                 if (iflist)
2893                                         iflist->prev = NULL;
2894                                 else
2895                                         ifend = NULL;
2896                         }
2897                         destroy_dahdi_pvt(&cur);
2898                 }
2899         } else {
2900                 if (prev) {
2901                         prev->next = cur->next;
2902                         if (prev->next)
2903                                 prev->next->prev = prev;
2904                         else
2905                                 ifend = prev;
2906                 } else {
2907                         iflist = cur->next;
2908                         if (iflist)
2909                                 iflist->prev = NULL;
2910                         else
2911                                 ifend = NULL;
2912                 }
2913                 destroy_dahdi_pvt(&cur);
2914         }
2915         return 0;
2916 }
2917
2918 static void destroy_all_channels(void)
2919 {
2920         int x;
2921         struct dahdi_pvt *p, *pl;
2922
2923         while (num_restart_pending) {
2924                 usleep(1);
2925         }
2926
2927         ast_mutex_lock(&iflock);
2928         /* Destroy all the interfaces and free their memory */
2929         p = iflist;
2930         while (p) {
2931                 /* Free any callerid */
2932                 if (p->cidspill)
2933                         ast_free(p->cidspill);
2934                 pl = p;
2935                 p = p->next;
2936                 x = pl->channel;
2937                 /* Free associated memory */
2938                 if (pl)
2939                         destroy_dahdi_pvt(&pl);
2940                 if (option_verbose > 2) 
2941                         ast_verbose(VERBOSE_PREFIX_2 "Unregistered channel %d\n", x);
2942         }
2943         iflist = NULL;
2944         ifcount = 0;
2945         ast_mutex_unlock(&iflock);
2946 }
2947
2948 #ifdef HAVE_PRI
2949 static char *dahdi_send_keypad_facility_app = "DAHDISendKeypadFacility";
2950
2951 static int dahdi_send_keypad_facility_exec(struct ast_channel *chan, void *data)
2952 {
2953         /* Data will be our digit string */
2954         struct dahdi_pvt *p;
2955         char *digits = (char *) data;
2956
2957         if (ast_strlen_zero(digits)) {
2958                 ast_debug(1, "No digit string sent to application!\n");
2959                 return -1;
2960         }
2961
2962         p = (struct dahdi_pvt *)chan->tech_pvt;
2963
2964         if (!p) {
2965                 ast_debug(1, "Unable to find technology private\n");
2966                 return -1;
2967         }
2968
2969         ast_mutex_lock(&p->lock);
2970
2971         if (!p->pri || !p->call) {
2972                 ast_debug(1, "Unable to find pri or call on channel!\n");
2973                 ast_mutex_unlock(&p->lock);
2974                 return -1;
2975         }
2976
2977         if (!pri_grab(p, p->pri)) {
2978                 pri_keypad_facility(p->pri->pri, p->call, digits);
2979                 pri_rel(p->pri);
2980         } else {
2981                 ast_debug(1, "Unable to grab pri to send keypad facility!\n");
2982                 ast_mutex_unlock(&p->lock);
2983                 return -1;
2984         }
2985
2986         ast_mutex_unlock(&p->lock);
2987
2988         return 0;
2989 }
2990
2991 static char *dahdi_send_callrerouting_facility_app = "DAHDISendCallreroutingFacility";
2992
2993 static int dahdi_send_callrerouting_facility_exec(struct ast_channel *chan, void *data)
2994 {
2995         /* Data will be our digit string */
2996         struct dahdi_pvt *p;
2997         char *parse, *tok, *tokb;
2998         char *dest = NULL;
2999         char *original = NULL;
3000         char *reason = NULL;
3001         int res = -1;
3002
3003         if (ast_strlen_zero(data)) {
3004                 ast_log(LOG_DEBUG, "No data sent to application!\n");
3005                 return -1;
3006         }
3007
3008         p = (struct dahdi_pvt *)chan->tech_pvt;
3009
3010         if (!p) {
3011                 ast_log(LOG_DEBUG, "Unable to find technology private\n");
3012                 return -1;
3013         }
3014
3015
3016         parse = ast_strdupa(data);
3017         tok = strtok_r(parse, "|", &tokb);
3018
3019         if (!tok) {
3020                 ast_log(LOG_WARNING, "callrerouting facility requires at least destination number argument\n");
3021                 return -1;
3022         }
3023         dest = tok;     
3024
3025         tok = strtok_r(NULL, "|", &tokb);
3026         if (!tok) {
3027                 ast_log(LOG_WARNING, "Callrerouting Facility without original called number argument\n");
3028         } else {
3029                 original = tok;
3030         }
3031
3032         tok = strtok_r(NULL, "|", &tokb);
3033         if (!tok) {
3034                 ast_log(LOG_NOTICE, "Callrerouting Facility without diversion reason argument, defaulting to unknown\n");
3035         } else {
3036                 reason = tok;
3037         }
3038
3039         ast_mutex_lock(&p->lock);
3040
3041         if (!p->pri || !p->call) {
3042                 ast_log(LOG_DEBUG, "Unable to find pri or call on channel!\n");
3043                 ast_mutex_unlock(&p->lock);
3044                 return -1;
3045         }
3046
3047         switch (p->sig) {
3048         case SIG_PRI:
3049                 if (!pri_grab(p, p->pri)) {
3050                         if (chan->_state == AST_STATE_RING)
3051                                 res = pri_callrerouting_facility(p->pri->pri, p->call, dest, original, reason);
3052                         pri_rel(p->pri);
3053                 } else {
3054                         ast_log(LOG_DEBUG, "Unable to grab pri to send callrerouting facility on span %d!\n", p->span);
3055                         ast_mutex_unlock(&p->lock);