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