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