6783126312d8b6cd45eef3893b0c1f2217726dee
[asterisk/asterisk.git] / channels / chan_dahdi.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2008, 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  * \ingroup channel_drivers
33  *
34  * \todo Deprecate the "musiconhold" configuration option post 1.4
35  */
36
37 /*!
38  * \li The channel chan_dahdi uses the configuration file \ref chan_dahdi.conf
39  * \addtogroup configuration_file
40  */
41
42 /*! \page chan_dahdi.conf chan_dahdi.conf
43  * \verbinclude chan_dahdi.conf.sample
44  */
45
46 /*** MODULEINFO
47         <use type="module">res_smdi</use>
48         <depend>dahdi</depend>
49         <depend>tonezone</depend>
50         <use type="external">pri</use>
51         <use type="external">ss7</use>
52         <use type="external">openr2</use>
53         <support_level>core</support_level>
54  ***/
55
56 #include "asterisk.h"
57
58 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
59
60 #if defined(__NetBSD__) || defined(__FreeBSD__)
61 #include <pthread.h>
62 #include <signal.h>
63 #else
64 #include <sys/signal.h>
65 #endif
66 #include <sys/ioctl.h>
67 #include <sys/stat.h>
68 #include <math.h>
69 #include <ctype.h>
70
71 #include <dahdi/user.h>
72 #include <dahdi/tonezone.h>
73 #include "sig_analog.h"
74 /* Analog signaling is currently still present in chan_dahdi for use with
75  * radio. Sig_analog does not currently handle any radio operations. If
76  * radio only uses analog signaling, then the radio handling logic could
77  * be placed in sig_analog and the duplicated code could be removed.
78  */
79
80 #if defined(HAVE_PRI)
81 #include "sig_pri.h"
82 #ifndef PRI_RESTART
83 #error "Upgrade your libpri"
84 #endif
85 #endif  /* defined(HAVE_PRI) */
86
87 #if defined(HAVE_SS7)
88 #include "sig_ss7.h"
89 #if defined(LIBSS7_ABI_COMPATIBILITY)
90 #error "Your installed libss7 is not compatible"
91 #endif
92 #endif  /* defined(HAVE_SS7) */
93
94 #ifdef HAVE_OPENR2
95 /* put this here until sig_mfcr2 comes along */
96 #define SIG_MFCR2_MAX_CHANNELS  672             /*!< No more than a DS3 per trunk group */
97 #include <openr2.h>
98 #endif
99
100 #include "asterisk/lock.h"
101 #include "asterisk/channel.h"
102 #include "asterisk/config.h"
103 #include "asterisk/module.h"
104 #include "asterisk/pbx.h"
105 #include "asterisk/file.h"
106 #include "asterisk/ulaw.h"
107 #include "asterisk/alaw.h"
108 #include "asterisk/callerid.h"
109 #include "asterisk/adsi.h"
110 #include "asterisk/cli.h"
111 #include "asterisk/cdr.h"
112 #include "asterisk/cel.h"
113 #include "asterisk/features.h"
114 #include "asterisk/musiconhold.h"
115 #include "asterisk/say.h"
116 #include "asterisk/tdd.h"
117 #include "asterisk/app.h"
118 #include "asterisk/dsp.h"
119 #include "asterisk/astdb.h"
120 #include "asterisk/manager.h"
121 #include "asterisk/causes.h"
122 #include "asterisk/term.h"
123 #include "asterisk/utils.h"
124 #include "asterisk/transcap.h"
125 #include "asterisk/stringfields.h"
126 #include "asterisk/abstract_jb.h"
127 #include "asterisk/smdi.h"
128 #include "asterisk/astobj.h"
129 #include "asterisk/event.h"
130 #include "asterisk/devicestate.h"
131 #include "asterisk/paths.h"
132 #include "asterisk/ccss.h"
133 #include "asterisk/data.h"
134
135 /*** DOCUMENTATION
136         <application name="DAHDISendKeypadFacility" language="en_US">
137                 <synopsis>
138                         Send digits out of band over a PRI.
139                 </synopsis>
140                 <syntax>
141                         <parameter name="digits" required="true" />
142                 </syntax>
143                 <description>
144                         <para>This application will send the given string of digits in a Keypad
145                         Facility IE over the current channel.</para>
146                 </description>
147         </application>
148         <application name="DAHDISendCallreroutingFacility" language="en_US">
149                 <synopsis>
150                         Send an ISDN call rerouting/deflection facility message.
151                 </synopsis>
152                 <syntax argsep=",">
153                         <parameter name="destination" required="true">
154                                 <para>Destination number.</para>
155                         </parameter>
156                         <parameter name="original">
157                                 <para>Original called number.</para>
158                         </parameter>
159                         <parameter name="reason">
160                                 <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
161                         </parameter>
162                 </syntax>
163                 <description>
164                         <para>This application will send an ISDN switch specific call
165                         rerouting/deflection facility message over the current channel.
166                         Supported switches depend upon the version of libpri in use.</para>
167                 </description>
168         </application>
169         <application name="DAHDIAcceptR2Call" language="en_US">
170                 <synopsis>
171                         Accept an R2 call if its not already accepted (you still need to answer it)
172                 </synopsis>
173                 <syntax>
174                         <parameter name="charge" required="true">
175                                 <para>Yes or No.</para>
176                                 <para>Whether you want to accept the call with charge or without charge.</para>
177                         </parameter>
178                 </syntax>
179                 <description>
180                         <para>This application will Accept the R2 call either with charge or no charge.</para>
181                 </description>
182         </application>
183         <manager name="DAHDITransfer" language="en_US">
184                 <synopsis>
185                         Transfer DAHDI Channel.
186                 </synopsis>
187                 <syntax>
188                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
189                         <parameter name="DAHDIChannel" required="true">
190                                 <para>DAHDI channel number to transfer.</para>
191                         </parameter>
192                 </syntax>
193                 <description>
194                         <para>Simulate a flash hook event by the user connected to the channel.</para>
195                         <note><para>Valid only for analog channels.</para></note>
196                 </description>
197         </manager>
198         <manager name="DAHDIHangup" language="en_US">
199                 <synopsis>
200                         Hangup DAHDI Channel.
201                 </synopsis>
202                 <syntax>
203                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
204                         <parameter name="DAHDIChannel" required="true">
205                                 <para>DAHDI channel number to hangup.</para>
206                         </parameter>
207                 </syntax>
208                 <description>
209                         <para>Simulate an on-hook event by the user connected to the channel.</para>
210                         <note><para>Valid only for analog channels.</para></note>
211                 </description>
212         </manager>
213         <manager name="DAHDIDialOffhook" language="en_US">
214                 <synopsis>
215                         Dial over DAHDI channel while offhook.
216                 </synopsis>
217                 <syntax>
218                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
219                         <parameter name="DAHDIChannel" required="true">
220                                 <para>DAHDI channel number to dial digits.</para>
221                         </parameter>
222                         <parameter name="Number" required="true">
223                                 <para>Digits to dial.</para>
224                         </parameter>
225                 </syntax>
226                 <description>
227                         <para>Generate DTMF control frames to the bridged peer.</para>
228                 </description>
229         </manager>
230         <manager name="DAHDIDNDon" language="en_US">
231                 <synopsis>
232                         Toggle DAHDI channel Do Not Disturb status ON.
233                 </synopsis>
234                 <syntax>
235                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
236                         <parameter name="DAHDIChannel" required="true">
237                                 <para>DAHDI channel number to set DND on.</para>
238                         </parameter>
239                 </syntax>
240                 <description>
241                         <para>Equivalent to the CLI command "dahdi set dnd <variable>channel</variable> on".</para>
242                         <note><para>Feature only supported by analog channels.</para></note>
243                 </description>
244         </manager>
245         <manager name="DAHDIDNDoff" language="en_US">
246                 <synopsis>
247                         Toggle DAHDI channel Do Not Disturb status OFF.
248                 </synopsis>
249                 <syntax>
250                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
251                         <parameter name="DAHDIChannel" required="true">
252                                 <para>DAHDI channel number to set DND off.</para>
253                         </parameter>
254                 </syntax>
255                 <description>
256                         <para>Equivalent to the CLI command "dahdi set dnd <variable>channel</variable> off".</para>
257                         <note><para>Feature only supported by analog channels.</para></note>
258                 </description>
259         </manager>
260         <manager name="DAHDIShowChannels" language="en_US">
261                 <synopsis>
262                         Show status of DAHDI channels.
263                 </synopsis>
264                 <syntax>
265                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
266                         <parameter name="DAHDIChannel">
267                                 <para>Specify the specific channel number to show.  Show all channels if zero or not present.</para>
268                         </parameter>
269                 </syntax>
270                 <description>
271                         <para>Similar to the CLI command "dahdi show channels".</para>
272                 </description>
273         </manager>
274         <manager name="DAHDIRestart" language="en_US">
275                 <synopsis>
276                         Fully Restart DAHDI channels (terminates calls).
277                 </synopsis>
278                 <syntax>
279                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
280                 </syntax>
281                 <description>
282                         <para>Equivalent to the CLI command "dahdi restart".</para>
283                 </description>
284         </manager>
285         <manager name="PRIShowSpans" language="en_US">
286                 <synopsis>
287                         Show status of PRI spans.
288                 </synopsis>
289                 <syntax>
290                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
291                         <parameter name="Span">
292                                 <para>Specify the specific span to show.  Show all spans if zero or not present.</para>
293                         </parameter>
294                 </syntax>
295                 <description>
296                         <para>Similar to the CLI command "pri show spans".</para>
297                 </description>
298         </manager>
299  ***/
300
301 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
302
303 static const char * const lbostr[] = {
304 "0 db (CSU)/0-133 feet (DSX-1)",
305 "133-266 feet (DSX-1)",
306 "266-399 feet (DSX-1)",
307 "399-533 feet (DSX-1)",
308 "533-655 feet (DSX-1)",
309 "-7.5db (CSU)",
310 "-15db (CSU)",
311 "-22.5db (CSU)"
312 };
313
314 /*! Global jitterbuffer configuration - by default, jb is disabled
315  *  \note Values shown here match the defaults shown in chan_dahdi.conf.sample */
316 static struct ast_jb_conf default_jbconf =
317 {
318         .flags = 0,
319         .max_size = 200,
320         .resync_threshold = 1000,
321         .impl = "fixed",
322         .target_extra = 40,
323 };
324 static struct ast_jb_conf global_jbconf;
325
326 /*!
327  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
328  * the user hangs up to reset the state machine so ring works properly.
329  * This is used to be able to support kewlstart by putting the zhone in
330  * groundstart mode since their forward disconnect supervision is entirely
331  * broken even though their documentation says it isn't and their support
332  * is entirely unwilling to provide any assistance with their channel banks
333  * even though their web site says they support their products for life.
334  */
335 /* #define ZHONE_HACK */
336
337 /*! \brief Typically, how many rings before we should send Caller*ID */
338 #define DEFAULT_CIDRINGS 1
339
340 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
341
342
343 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
344 #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))
345
346 static const char tdesc[] = "DAHDI Telephony Driver"
347 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
348         " w/"
349         #if defined(HAVE_PRI)
350                 "PRI"
351         #endif  /* defined(HAVE_PRI) */
352         #if defined(HAVE_SS7)
353                 #if defined(HAVE_PRI)
354                 " & "
355                 #endif  /* defined(HAVE_PRI) */
356                 "SS7"
357         #endif  /* defined(HAVE_SS7) */
358         #if defined(HAVE_OPENR2)
359                 #if defined(HAVE_PRI) || defined(HAVE_SS7)
360                 " & "
361                 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
362                 "MFC/R2"
363         #endif  /* defined(HAVE_OPENR2) */
364 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2) */
365 ;
366
367 static const char config[] = "chan_dahdi.conf";
368
369 #define SIG_EM          DAHDI_SIG_EM
370 #define SIG_EMWINK      (0x0100000 | DAHDI_SIG_EM)
371 #define SIG_FEATD       (0x0200000 | DAHDI_SIG_EM)
372 #define SIG_FEATDMF     (0x0400000 | DAHDI_SIG_EM)
373 #define SIG_FEATB       (0x0800000 | DAHDI_SIG_EM)
374 #define SIG_E911        (0x1000000 | DAHDI_SIG_EM)
375 #define SIG_FEATDMF_TA  (0x2000000 | DAHDI_SIG_EM)
376 #define SIG_FGC_CAMA    (0x4000000 | DAHDI_SIG_EM)
377 #define SIG_FGC_CAMAMF  (0x8000000 | DAHDI_SIG_EM)
378 #define SIG_FXSLS       DAHDI_SIG_FXSLS
379 #define SIG_FXSGS       DAHDI_SIG_FXSGS
380 #define SIG_FXSKS       DAHDI_SIG_FXSKS
381 #define SIG_FXOLS       DAHDI_SIG_FXOLS
382 #define SIG_FXOGS       DAHDI_SIG_FXOGS
383 #define SIG_FXOKS       DAHDI_SIG_FXOKS
384 #define SIG_PRI         DAHDI_SIG_CLEAR
385 #define SIG_BRI         (0x2000000 | DAHDI_SIG_CLEAR)
386 #define SIG_BRI_PTMP    (0X4000000 | DAHDI_SIG_CLEAR)
387 #define SIG_SS7         (0x1000000 | DAHDI_SIG_CLEAR)
388 #define SIG_MFCR2       DAHDI_SIG_CAS
389 #define SIG_SF          DAHDI_SIG_SF
390 #define SIG_SFWINK      (0x0100000 | DAHDI_SIG_SF)
391 #define SIG_SF_FEATD    (0x0200000 | DAHDI_SIG_SF)
392 #define SIG_SF_FEATDMF  (0x0400000 | DAHDI_SIG_SF)
393 #define SIG_SF_FEATB    (0x0800000 | DAHDI_SIG_SF)
394 #define SIG_EM_E1       DAHDI_SIG_EM_E1
395
396 #ifdef LOTS_OF_SPANS
397 #define NUM_SPANS       DAHDI_MAX_SPANS
398 #else
399 #define NUM_SPANS               32
400 #endif
401
402 #define CHAN_PSEUDO     -2
403
404 #define CALLPROGRESS_PROGRESS           1
405 #define CALLPROGRESS_FAX_OUTGOING       2
406 #define CALLPROGRESS_FAX_INCOMING       4
407 #define CALLPROGRESS_FAX                (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
408
409 #define NUM_CADENCE_MAX 25
410 static int num_cadence = 4;
411 static int user_has_defined_cadences = 0;
412
413 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
414         { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
415         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
416         { { 125, 125, 125, 125, 125, 4000 } },  /*!< Three short bursts */
417         { { 1000, 500, 2500, 5000 } },  /*!< Long ring */
418 };
419
420 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
421  * is 1, the second pause is 2 and so on.
422  */
423
424 static int cidrings[NUM_CADENCE_MAX] = {
425         2,                                                                              /*!< Right after first long ring */
426         4,                                                                              /*!< Right after long part */
427         3,                                                                              /*!< After third chirp */
428         2,                                                                              /*!< Second spell */
429 };
430
431 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
432 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
433
434 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
435                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
436
437 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
438 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
439
440 static char defaultcic[64] = "";
441 static char defaultozz[64] = "";
442
443 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
444 static char mwimonitornotify[PATH_MAX] = "";
445 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
446 static int  mwisend_rpas = 0;
447 #endif
448
449 static char progzone[10] = "";
450
451 static int usedistinctiveringdetection = 0;
452 static int distinctiveringaftercid = 0;
453
454 static int numbufs = 4;
455
456 static int mwilevel = 512;
457 static int dtmfcid_level = 256;
458
459 #define REPORT_CHANNEL_ALARMS 1
460 #define REPORT_SPAN_ALARMS    2 
461 static int report_alarms = REPORT_CHANNEL_ALARMS;
462
463 #ifdef HAVE_PRI
464 static int pridebugfd = -1;
465 static char pridebugfilename[1024] = "";
466 #endif
467
468 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
469 static int firstdigittimeout = 16000;
470
471 /*! \brief How long to wait for following digits (FXO logic) */
472 static int gendigittimeout = 8000;
473
474 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
475 static int matchdigittimeout = 3000;
476
477 /*! \brief Protect the interface list (of dahdi_pvt's) */
478 AST_MUTEX_DEFINE_STATIC(iflock);
479
480
481 static int ifcount = 0;
482
483 #ifdef HAVE_PRI
484 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
485 #endif
486
487 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
488    when it's doing something critical. */
489 AST_MUTEX_DEFINE_STATIC(monlock);
490
491 /*! \brief This is the thread for the monitor which checks for input on the channels
492    which are not currently in use. */
493 static pthread_t monitor_thread = AST_PTHREADT_NULL;
494 static ast_cond_t ss_thread_complete;
495 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
496 AST_MUTEX_DEFINE_STATIC(restart_lock);
497 static int ss_thread_count = 0;
498 static int num_restart_pending = 0;
499
500 static int restart_monitor(void);
501
502 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);
503
504 static int dahdi_sendtext(struct ast_channel *c, const char *text);
505
506 static void mwi_event_cb(const struct ast_event *event, void *userdata)
507 {
508         /* This module does not handle MWI in an event-based manner.  However, it
509          * subscribes to MWI for each mailbox that is configured so that the core
510          * knows that we care about it.  Then, chan_dahdi will get the MWI from the
511          * event cache instead of checking the mailbox directly. */
512 }
513
514 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
515 static inline int dahdi_get_event(int fd)
516 {
517         int j;
518         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
519                 return -1;
520         return j;
521 }
522
523 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
524 static inline int dahdi_wait_event(int fd)
525 {
526         int i, j = 0;
527         i = DAHDI_IOMUX_SIGEVENT;
528         if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
529                 return -1;
530         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
531                 return -1;
532         return j;
533 }
534
535 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
536 #define READ_SIZE 160
537
538 #define MASK_AVAIL              (1 << 0)        /*!< Channel available for PRI use */
539 #define MASK_INUSE              (1 << 1)        /*!< Channel currently in use */
540
541 #define CALLWAITING_SILENT_SAMPLES              ((300 * 8) / READ_SIZE) /*!< 300 ms */
542 #define CALLWAITING_REPEAT_SAMPLES              ((10000 * 8) / READ_SIZE) /*!< 10,000 ms */
543 #define CALLWAITING_SUPPRESS_SAMPLES    ((100 * 8) / READ_SIZE) /*!< 100 ms */
544 #define CIDCW_EXPIRE_SAMPLES                    ((500 * 8) / READ_SIZE) /*!< 500 ms */
545 #define MIN_MS_SINCE_FLASH                              ((2000) )       /*!< 2000 ms */
546 #define DEFAULT_RINGT                                   ((8000 * 8) / READ_SIZE) /*!< 8,000 ms */
547 #define DEFAULT_DIALTONE_DETECT_TIMEOUT ((10000 * 8) / READ_SIZE) /*!< 10,000 ms */
548
549 struct dahdi_pvt;
550
551 /*!
552  * \brief Configured ring timeout base.
553  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
554  */
555 static int ringt_base = DEFAULT_RINGT;
556
557 #if defined(HAVE_SS7)
558
559 struct dahdi_ss7 {
560         struct sig_ss7_linkset ss7;
561 };
562
563 static struct dahdi_ss7 linksets[NUM_SPANS];
564
565 static int cur_ss7type = -1;
566 static int cur_linkset = -1;
567 static int cur_pointcode = -1;
568 static int cur_cicbeginswith = -1;
569 static int cur_adjpointcode = -1;
570 static int cur_networkindicator = -1;
571 static int cur_defaultdpc = -1;
572 #endif  /* defined(HAVE_SS7) */
573
574 #ifdef HAVE_OPENR2
575 struct dahdi_mfcr2 {
576         pthread_t r2master;                    /*!< Thread of master */
577         openr2_context_t *protocol_context;    /*!< OpenR2 context handle */
578         struct dahdi_pvt *pvts[SIG_MFCR2_MAX_CHANNELS];     /*!< Member channel pvt structs */
579         int numchans;                          /*!< Number of channels in this R2 block */
580         int monitored_count;                   /*!< Number of channels being monitored */
581 };
582
583 struct dahdi_mfcr2_conf {
584         openr2_variant_t variant;
585         int mfback_timeout;
586         int metering_pulse_timeout;
587         int max_ani;
588         int max_dnis;
589 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 2
590         int dtmf_time_on;
591         int dtmf_time_off;
592 #endif
593 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 3
594         int dtmf_end_timeout;
595 #endif
596         signed int get_ani_first:2;
597 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
598         signed int skip_category_request:2;
599 #endif
600         unsigned int call_files:1;
601         unsigned int allow_collect_calls:1;
602         unsigned int charge_calls:1;
603         unsigned int accept_on_offer:1;
604         unsigned int forced_release:1;
605         unsigned int double_answer:1;
606         signed int immediate_accept:2;
607 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 2
608         signed int dtmf_dialing:2;
609         signed int dtmf_detection:2;
610 #endif
611         char logdir[OR2_MAX_PATH];
612         char r2proto_file[OR2_MAX_PATH];
613         openr2_log_level_t loglevel;
614         openr2_calling_party_category_t category;
615 };
616
617 /* malloc'd array of malloc'd r2links */
618 static struct dahdi_mfcr2 **r2links;
619 /* how many r2links have been malloc'd */
620 static int r2links_count = 0;
621
622 #endif /* HAVE_OPENR2 */
623
624 #ifdef HAVE_PRI
625
626 struct dahdi_pri {
627         int dchannels[SIG_PRI_NUM_DCHANS];              /*!< What channel are the dchannels on */
628         int mastertrunkgroup;                                   /*!< What trunk group is our master */
629         int prilogicalspan;                                             /*!< Logical span number within trunk group */
630         struct sig_pri_span pri;
631 };
632
633 static struct dahdi_pri pris[NUM_SPANS];
634
635 #if defined(HAVE_PRI_CCSS)
636 /*! DAHDI PRI CCSS agent and monitor type name. */
637 static const char dahdi_pri_cc_type[] = "DAHDI/PRI";
638 #endif  /* defined(HAVE_PRI_CCSS) */
639
640 #else
641 /*! Shut up the compiler */
642 struct dahdi_pri;
643 #endif
644
645 #define SUB_REAL        0                       /*!< Active call */
646 #define SUB_CALLWAIT    1                       /*!< Call-Waiting call on hold */
647 #define SUB_THREEWAY    2                       /*!< Three-way call */
648
649 /* Polarity states */
650 #define POLARITY_IDLE   0
651 #define POLARITY_REV    1
652
653
654 struct distRingData {
655         int ring[3];
656         int range;
657 };
658 struct ringContextData {
659         char contextData[AST_MAX_CONTEXT];
660 };
661 struct dahdi_distRings {
662         struct distRingData ringnum[3];
663         struct ringContextData ringContext[3];
664 };
665
666 static const char * const subnames[] = {
667         "Real",
668         "Callwait",
669         "Threeway"
670 };
671
672 struct dahdi_subchannel {
673         int dfd;
674         struct ast_channel *owner;
675         int chan;
676         short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
677         struct ast_frame f;             /*!< One frame for each channel.  How did this ever work before? */
678         unsigned int needringing:1;
679         unsigned int needbusy:1;
680         unsigned int needcongestion:1;
681         unsigned int needanswer:1;
682         unsigned int needflash:1;
683         unsigned int needhold:1;
684         unsigned int needunhold:1;
685         unsigned int linear:1;
686         unsigned int inthreeway:1;
687         struct dahdi_confinfo curconf;
688 };
689
690 #define CONF_USER_REAL          (1 << 0)
691 #define CONF_USER_THIRDCALL     (1 << 1)
692
693 #define MAX_SLAVES      4
694
695 /* States for sending MWI message
696  * First three states are required for send Ring Pulse Alert Signal
697  */
698 typedef enum {
699         MWI_SEND_NULL = 0,
700         MWI_SEND_SA,
701         MWI_SEND_SA_WAIT,
702         MWI_SEND_PAUSE,
703         MWI_SEND_SPILL,
704         MWI_SEND_CLEANUP,
705         MWI_SEND_DONE,
706 } mwisend_states;
707
708 struct mwisend_info {
709         struct  timeval pause;
710         mwisend_states  mwisend_current;
711 };
712
713 /*! Specify the lists dahdi_pvt can be put in. */
714 enum DAHDI_IFLIST {
715         DAHDI_IFLIST_NONE,      /*!< The dahdi_pvt is not in any list. */
716         DAHDI_IFLIST_MAIN,      /*!< The dahdi_pvt is in the main interface list */
717 #if defined(HAVE_PRI)
718         DAHDI_IFLIST_NO_B_CHAN, /*!< The dahdi_pvt is in a no B channel interface list */
719 #endif  /* defined(HAVE_PRI) */
720 };
721
722 struct dahdi_pvt {
723         ast_mutex_t lock;                                       /*!< Channel private lock. */
724         struct callerid_state *cs;
725         struct ast_channel *owner;                      /*!< Our current active owner (if applicable) */
726                                                         /*!< Up to three channels can be associated with this call */
727
728         struct dahdi_subchannel sub_unused;             /*!< Just a safety precaution */
729         struct dahdi_subchannel subs[3];                        /*!< Sub-channels */
730         struct dahdi_confinfo saveconf;                 /*!< Saved conference info */
731
732         struct dahdi_pvt *slaves[MAX_SLAVES];           /*!< Slave to us (follows our conferencing) */
733         struct dahdi_pvt *master;                               /*!< Master to us (we follow their conferencing) */
734         int inconference;                               /*!< If our real should be in the conference */
735
736         int bufsize;                /*!< Size of the buffers */
737         int buf_no;                                     /*!< Number of buffers */
738         int buf_policy;                         /*!< Buffer policy */
739         int faxbuf_no;              /*!< Number of Fax buffers */
740         int faxbuf_policy;          /*!< Fax buffer policy */
741         int sig;                                        /*!< Signalling style */
742         /*!
743          * \brief Nonzero if the signaling type is sent over a radio.
744          * \note Set to a couple of nonzero values but it is only tested like a boolean.
745          */
746         int radio;
747         int outsigmod;                                  /*!< Outbound Signalling style (modifier) */
748         int oprmode;                                    /*!< "Operator Services" mode */
749         struct dahdi_pvt *oprpeer;                              /*!< "Operator Services" peer tech_pvt ptr */
750         /*! \brief Amount of gain to increase during caller id */
751         float cid_rxgain;
752         /*! \brief Rx gain set by chan_dahdi.conf */
753         float rxgain;
754         /*! \brief Tx gain set by chan_dahdi.conf */
755         float txgain;
756
757         float txdrc; /*!< Dynamic Range Compression factor. a number between 1 and 6ish */
758         float rxdrc;
759         
760         int tonezone;                                   /*!< tone zone for this chan, or -1 for default */
761         enum DAHDI_IFLIST which_iflist; /*!< Which interface list is this structure listed? */
762         struct dahdi_pvt *next;                         /*!< Next channel in list */
763         struct dahdi_pvt *prev;                         /*!< Prev channel in list */
764
765         /* flags */
766
767         /*!
768          * \brief TRUE if ADSI (Analog Display Services Interface) available
769          * \note Set from the "adsi" value read in from chan_dahdi.conf
770          */
771         unsigned int adsi:1;
772         /*!
773          * \brief TRUE if we can use a polarity reversal to mark when an outgoing
774          * call is answered by the remote party.
775          * \note Set from the "answeronpolarityswitch" value read in from chan_dahdi.conf
776          */
777         unsigned int answeronpolarityswitch:1;
778         /*!
779          * \brief TRUE if busy detection is enabled.
780          * (Listens for the beep-beep busy pattern.)
781          * \note Set from the "busydetect" value read in from chan_dahdi.conf
782          */
783         unsigned int busydetect:1;
784         /*!
785          * \brief TRUE if call return is enabled.
786          * (*69, if your dialplan doesn't catch this first)
787          * \note Set from the "callreturn" value read in from chan_dahdi.conf
788          */
789         unsigned int callreturn:1;
790         /*!
791          * \brief TRUE if busy extensions will hear the call-waiting tone
792          * and can use hook-flash to switch between callers.
793          * \note Can be disabled by dialing *70.
794          * \note Initialized with the "callwaiting" value read in from chan_dahdi.conf
795          */
796         unsigned int callwaiting:1;
797         /*!
798          * \brief TRUE if send caller ID for Call Waiting
799          * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
800          */
801         unsigned int callwaitingcallerid:1;
802         /*!
803          * \brief TRUE if support for call forwarding enabled.
804          * Dial *72 to enable call forwarding.
805          * Dial *73 to disable call forwarding.
806          * \note Set from the "cancallforward" value read in from chan_dahdi.conf
807          */
808         unsigned int cancallforward:1;
809         /*!
810          * \brief TRUE if support for call parking is enabled.
811          * \note Set from the "canpark" value read in from chan_dahdi.conf
812          */
813         unsigned int canpark:1;
814         /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
815         unsigned int confirmanswer:1;
816         /*!
817          * \brief TRUE if the channel is to be destroyed on hangup.
818          * (Used by pseudo channels.)
819          */
820         unsigned int destroy:1;
821         unsigned int didtdd:1;                          /*!< flag to say its done it once */
822         /*! \brief TRUE if analog type line dialed no digits in Dial() */
823         unsigned int dialednone:1;
824         /*!
825          * \brief TRUE if in the process of dialing digits or sending something.
826          * \note This is used as a receive squelch for ISDN until connected.
827          */
828         unsigned int dialing:1;
829         /*! \brief TRUE if the transfer capability of the call is digital. */
830         unsigned int digital:1;
831         /*! \brief TRUE if Do-Not-Disturb is enabled, present only for non sig_analog */
832         unsigned int dnd:1;
833         /*! \brief XXX BOOLEAN Purpose??? */
834         unsigned int echobreak:1;
835         /*!
836          * \brief TRUE if echo cancellation enabled when bridged.
837          * \note Initialized with the "echocancelwhenbridged" value read in from chan_dahdi.conf
838          * \note Disabled if the echo canceller is not setup.
839          */
840         unsigned int echocanbridged:1;
841         /*! \brief TRUE if echo cancellation is turned on. */
842         unsigned int echocanon:1;
843         /*! \brief TRUE if a fax tone has already been handled. */
844         unsigned int faxhandled:1;
845         /*! TRUE if dynamic faxbuffers are configured for use, default is OFF */
846         unsigned int usefaxbuffers:1;
847         /*! TRUE while buffer configuration override is in use */
848         unsigned int bufferoverrideinuse:1;
849         /*! \brief TRUE if over a radio and dahdi_read() has been called. */
850         unsigned int firstradio:1;
851         /*!
852          * \brief TRUE if the call will be considered "hung up" on a polarity reversal.
853          * \note Set from the "hanguponpolarityswitch" value read in from chan_dahdi.conf
854          */
855         unsigned int hanguponpolarityswitch:1;
856         /*! \brief TRUE if DTMF detection needs to be done by hardware. */
857         unsigned int hardwaredtmf:1;
858         /*!
859          * \brief TRUE if the outgoing caller ID is blocked/hidden.
860          * \note Caller ID can be disabled by dialing *67.
861          * \note Caller ID can be enabled by dialing *82.
862          * \note Initialized with the "hidecallerid" value read in from chan_dahdi.conf
863          */
864         unsigned int hidecallerid:1;
865         /*!
866          * \brief TRUE if hide just the name not the number for legacy PBX use.
867          * \note Only applies to PRI channels.
868          * \note Set from the "hidecalleridname" value read in from chan_dahdi.conf
869          */
870         unsigned int hidecalleridname:1;
871         /*! \brief TRUE if DTMF detection is disabled. */
872         unsigned int ignoredtmf:1;
873         /*!
874          * \brief TRUE if the channel should be answered immediately
875          * without attempting to gather any digits.
876          * \note Set from the "immediate" value read in from chan_dahdi.conf
877          */
878         unsigned int immediate:1;
879         /*! \brief TRUE if in an alarm condition. */
880         unsigned int inalarm:1;
881         /*! \brief TRUE if TDD in MATE mode */
882         unsigned int mate:1;
883         /*! \brief TRUE if we originated the call leg. */
884         unsigned int outgoing:1;
885         /* unsigned int overlapdial:1;                  unused and potentially confusing */
886         /*!
887          * \brief TRUE if busy extensions will hear the call-waiting tone
888          * and can use hook-flash to switch between callers.
889          * \note Set from the "callwaiting" value read in from chan_dahdi.conf
890          */
891         unsigned int permcallwaiting:1;
892         /*!
893          * \brief TRUE if the outgoing caller ID is blocked/restricted/hidden.
894          * \note Set from the "hidecallerid" value read in from chan_dahdi.conf
895          */
896         unsigned int permhidecallerid:1;
897         /*!
898          * \brief TRUE if PRI congestion/busy indications are sent out-of-band.
899          * \note Set from the "priindication" value read in from chan_dahdi.conf
900          */
901         unsigned int priindication_oob:1;
902         /*!
903          * \brief TRUE if PRI B channels are always exclusively selected.
904          * \note Set from the "priexclusive" value read in from chan_dahdi.conf
905          */
906         unsigned int priexclusive:1;
907         /*!
908          * \brief TRUE if we will pulse dial.
909          * \note Set from the "pulsedial" value read in from chan_dahdi.conf
910          */
911         unsigned int pulse:1;
912         /*! \brief TRUE if a pulsed digit was detected. (Pulse dial phone detected) */
913         unsigned int pulsedial:1;
914         unsigned int restartpending:1;          /*!< flag to ensure counted only once for restart */
915         /*!
916          * \brief TRUE if caller ID is restricted.
917          * \note Set but not used.  Should be deleted.  Redundant with permhidecallerid.
918          * \note Set from the "restrictcid" value read in from chan_dahdi.conf
919          */
920         unsigned int restrictcid:1;
921         /*!
922          * \brief TRUE if three way calling is enabled
923          * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
924          */
925         unsigned int threewaycalling:1;
926         /*!
927          * \brief TRUE if call transfer is enabled
928          * \note For FXS ports (either direct analog or over T1/E1):
929          *   Support flash-hook call transfer
930          * \note For digital ports using ISDN PRI protocols:
931          *   Support switch-side transfer (called 2BCT, RLT or other names)
932          * \note Set from the "transfer" value read in from chan_dahdi.conf
933          */
934         unsigned int transfer:1;
935         /*!
936          * \brief TRUE if caller ID is used on this channel.
937          * \note PRI and SS7 spans will save caller ID from the networking peer.
938          * \note FXS ports will generate the caller ID spill.
939          * \note FXO ports will listen for the caller ID spill.
940          * \note Set from the "usecallerid" value read in from chan_dahdi.conf
941          */
942         unsigned int use_callerid:1;
943         /*!
944          * \brief TRUE if we will use the calling presentation setting
945          * from the Asterisk channel for outgoing calls.
946          * \note Only applies to PRI and SS7 channels.
947          * \note Set from the "usecallingpres" value read in from chan_dahdi.conf
948          */
949         unsigned int use_callingpres:1;
950         /*!
951          * \brief TRUE if distinctive rings are to be detected.
952          * \note For FXO lines
953          * \note Set indirectly from the "usedistinctiveringdetection" value read in from chan_dahdi.conf
954          */
955         unsigned int usedistinctiveringdetection:1;
956         /*!
957          * \brief TRUE if we should use the callerid from incoming call on dahdi transfer.
958          * \note Set from the "useincomingcalleridondahditransfer" value read in from chan_dahdi.conf
959          */
960         unsigned int dahditrcallerid:1;
961         /*!
962          * \brief TRUE if allowed to flash-transfer to busy channels.
963          * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
964          */
965         unsigned int transfertobusy:1;
966         /*!
967          * \brief TRUE if the FXO port monitors for neon type MWI indications from the other end.
968          * \note Set if the "mwimonitor" value read in contains "neon" from chan_dahdi.conf
969          */
970         unsigned int mwimonitor_neon:1;
971         /*!
972          * \brief TRUE if the FXO port monitors for fsk type MWI indications from the other end.
973          * \note Set if the "mwimonitor" value read in contains "fsk" from chan_dahdi.conf
974          */
975         unsigned int mwimonitor_fsk:1;
976         /*!
977          * \brief TRUE if the FXO port monitors for rpas precursor to fsk MWI indications from the other end.
978          * \note RPAS - Ring Pulse Alert Signal
979          * \note Set if the "mwimonitor" value read in contains "rpas" from chan_dahdi.conf
980          */
981         unsigned int mwimonitor_rpas:1;
982         /*! \brief TRUE if an MWI monitor thread is currently active */
983         unsigned int mwimonitoractive:1;
984         /*! \brief TRUE if a MWI message sending thread is active */
985         unsigned int mwisendactive:1;
986         /*!
987          * \brief TRUE if channel is out of reset and ready
988          * \note Set but not used.
989          */
990         unsigned int inservice:1;
991         /*!
992          * \brief TRUE if the channel is locally blocked.
993          * \note Applies to SS7 and MFCR2 channels.
994          */
995         unsigned int locallyblocked:1;
996         /*!
997          * \brief TRUE if the channel is remotely blocked.
998          * \note Applies to SS7 and MFCR2 channels.
999          */
1000         unsigned int remotelyblocked:1;
1001         /*!
1002          * \brief TRUE if the channel alarms will be managed also as Span ones
1003          * \note Applies to all channels
1004          */
1005         unsigned int manages_span_alarms:1;
1006
1007 #if defined(HAVE_PRI)
1008         struct sig_pri_span *pri;
1009         int logicalspan;
1010 #endif
1011         /*!
1012          * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
1013          * \note Set from the "usesmdi" value read in from chan_dahdi.conf
1014          */
1015         unsigned int use_smdi:1;
1016         struct mwisend_info mwisend_data;
1017         /*! \brief The SMDI interface to get SMDI messages from. */
1018         struct ast_smdi_interface *smdi_iface;
1019
1020         /*! \brief Distinctive Ring data */
1021         struct dahdi_distRings drings;
1022
1023         /*!
1024          * \brief The configured context for incoming calls.
1025          * \note The "context" string read in from chan_dahdi.conf
1026          */
1027         char context[AST_MAX_CONTEXT];
1028         /*! 
1029          * \brief A description for the channel configuration
1030          * \note The "description" string read in from chan_dahdi.conf
1031          */
1032         char description[32];
1033         /*!
1034          * \brief Saved context string.
1035          */
1036         char defcontext[AST_MAX_CONTEXT];
1037         /*! \brief Extension to use in the dialplan. */
1038         char exten[AST_MAX_EXTENSION];
1039         /*!
1040          * \brief Language configured for calls.
1041          * \note The "language" string read in from chan_dahdi.conf
1042          */
1043         char language[MAX_LANGUAGE];
1044         /*!
1045          * \brief The configured music-on-hold class to use for calls.
1046          * \note The "musicclass" or "mohinterpret" or "musiconhold" string read in from chan_dahdi.conf
1047          */
1048         char mohinterpret[MAX_MUSICCLASS];
1049         /*!
1050          * \brief Suggested music-on-hold class for peer channel to use for calls.
1051          * \note The "mohsuggest" string read in from chan_dahdi.conf
1052          */
1053         char mohsuggest[MAX_MUSICCLASS];
1054         char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
1055 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1056         /*! \brief Automatic Number Identification number (Alternate PRI caller ID number) */
1057         char cid_ani[AST_MAX_EXTENSION];
1058 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
1059         /*! \brief Automatic Number Identification code from PRI */
1060         int cid_ani2;
1061         /*! \brief Caller ID number from an incoming call. */
1062         char cid_num[AST_MAX_EXTENSION];
1063         /*!
1064          * \brief Caller ID tag from incoming call
1065          * \note the "cid_tag" string read in from chan_dahdi.conf
1066          */
1067         char cid_tag[AST_MAX_EXTENSION];
1068         /*! \brief Caller ID Q.931 TON/NPI field values.  Set by PRI. Zero otherwise. */
1069         int cid_ton;
1070         /*! \brief Caller ID name from an incoming call. */
1071         char cid_name[AST_MAX_EXTENSION];
1072         /*! \brief Caller ID subaddress from an incoming call. */
1073         char cid_subaddr[AST_MAX_EXTENSION];
1074         char *origcid_num;                              /*!< malloced original callerid */
1075         char *origcid_name;                             /*!< malloced original callerid */
1076         /*! \brief Call waiting number. */
1077         char callwait_num[AST_MAX_EXTENSION];
1078         /*! \brief Call waiting name. */
1079         char callwait_name[AST_MAX_EXTENSION];
1080         /*! \brief Redirecting Directory Number Information Service (RDNIS) number */
1081         char rdnis[AST_MAX_EXTENSION];
1082         /*! \brief Dialed Number Identifier */
1083         char dnid[AST_MAX_EXTENSION];
1084         /*!
1085          * \brief Bitmapped groups this belongs to.
1086          * \note The "group" bitmapped group string read in from chan_dahdi.conf
1087          */
1088         ast_group_t group;
1089         /*! \brief Default call PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW. */
1090         int law_default;
1091         /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
1092         int law;
1093         int confno;                                     /*!< Our conference */
1094         int confusers;                                  /*!< Who is using our conference */
1095         int propconfno;                                 /*!< Propagated conference number */
1096         /*!
1097          * \brief Bitmapped call groups this belongs to.
1098          * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
1099          */
1100         ast_group_t callgroup;
1101         /*!
1102          * \brief Bitmapped pickup groups this belongs to.
1103          * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
1104          */
1105         ast_group_t pickupgroup;
1106         /*!
1107          * \brief Named call groups this belongs to.
1108          * \note The "namedcallgroup" string read in from chan_dahdi.conf
1109          */
1110         struct ast_namedgroups *named_callgroups;
1111         /*!
1112          * \brief Named pickup groups this belongs to.
1113          * \note The "namedpickupgroup" string read in from chan_dahdi.conf
1114          */
1115         struct ast_namedgroups *named_pickupgroups;
1116         /*!
1117          * \brief Channel variable list with associated values to set when a channel is created.
1118          * \note The "setvar" strings read in from chan_dahdi.conf
1119          */
1120         struct ast_variable *vars;
1121         int channel;                                    /*!< Channel Number */
1122         int span;                                       /*!< Span number */
1123         time_t guardtime;                               /*!< Must wait this much time before using for new call */
1124         int cid_signalling;                             /*!< CID signalling type bell202 or v23 */
1125         int cid_start;                                  /*!< CID start indicator, polarity or ring or DTMF without warning event */
1126         int dtmfcid_holdoff_state;              /*!< State indicator that allows for line to settle before checking for dtmf energy */
1127         struct timeval  dtmfcid_delay;  /*!< Time value used for allow line to settle */
1128         int callingpres;                                /*!< The value of calling presentation that we're going to use when placing a PRI call */
1129         int callwaitingrepeat;                          /*!< How many samples to wait before repeating call waiting */
1130         int cidcwexpire;                                /*!< When to stop waiting for CID/CW CAS response (In samples) */
1131         int cid_suppress_expire;                /*!< How many samples to suppress after a CID spill. */
1132         /*! \brief Analog caller ID waveform sample buffer */
1133         unsigned char *cidspill;
1134         /*! \brief Position in the cidspill buffer to send out next. */
1135         int cidpos;
1136         /*! \brief Length of the cidspill buffer containing samples. */
1137         int cidlen;
1138         /*! \brief Ring timeout timer?? */
1139         int ringt;
1140         /*!
1141          * \brief Ring timeout base.
1142          * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
1143          */
1144         int ringt_base;
1145         /*!
1146          * \brief Number of most significant digits/characters to strip from the dialed number.
1147          * \note Feature is deprecated.  Use dialplan logic.
1148          * \note The characters are stripped before the PRI TON/NPI prefix
1149          * characters are processed.
1150          */
1151         int stripmsd;
1152         /*!
1153          * \brief TRUE if Call Waiting (CW) CPE Alert Signal (CAS) is being sent.
1154          * \note
1155          * After CAS is sent, the call waiting caller id will be sent if the phone
1156          * gives a positive reply.
1157          */
1158         int callwaitcas;
1159         /*! \brief Number of call waiting rings. */
1160         int callwaitrings;
1161         /*! \brief Echo cancel parameters. */
1162         struct {
1163                 struct dahdi_echocanparams head;
1164                 struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
1165         } echocancel;
1166         /*!
1167          * \brief Echo training time. 0 = disabled
1168          * \note Set from the "echotraining" value read in from chan_dahdi.conf
1169          */
1170         int echotraining;
1171         /*! \brief Filled with 'w'.  XXX Purpose?? */
1172         char echorest[20];
1173         /*!
1174          * \brief Number of times to see "busy" tone before hanging up.
1175          * \note Set from the "busycount" value read in from chan_dahdi.conf
1176          */
1177         int busycount;
1178         /*!
1179          * \brief Busy cadence pattern description.
1180          * \note Set from the "busypattern" value read from chan_dahdi.conf
1181          */
1182         struct ast_dsp_busy_pattern busy_cadence;
1183         /*!
1184          * \brief Bitmapped call progress detection flags. CALLPROGRESS_xxx values.
1185          * \note Bits set from the "callprogress" and "faxdetect" values read in from chan_dahdi.conf
1186          */
1187         int callprogress;
1188         /*!
1189          * \brief Number of milliseconds to wait for dialtone.
1190          * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
1191          */
1192         int waitfordialtone;
1193         /*!
1194          * \brief Number of frames to watch for dialtone in incoming calls
1195          * \note Set from the "dialtone_detect" value read in from chan_dahdi.conf
1196          */
1197         int dialtone_detect;
1198         int dialtone_scanning_time_elapsed;     /*!< Amount of audio scanned for dialtone, in frames */
1199         struct timeval waitingfordt;                    /*!< Time we started waiting for dialtone */
1200         struct timeval flashtime;                       /*!< Last flash-hook time */
1201         /*! \brief Opaque DSP configuration structure. */
1202         struct ast_dsp *dsp;
1203         /*! \brief DAHDI dial operation command struct for ioctl() call. */
1204         struct dahdi_dialoperation dop;
1205         int whichwink;                                  /*!< SIG_FEATDMF_TA Which wink are we on? */
1206         /*! \brief Second part of SIG_FEATDMF_TA wink operation. */
1207         char finaldial[64];
1208         char accountcode[AST_MAX_ACCOUNT_CODE];         /*!< Account code */
1209         int amaflags;                                   /*!< AMA Flags */
1210         struct tdd_state *tdd;                          /*!< TDD flag */
1211         /*! \brief Accumulated call forwarding number. */
1212         char call_forward[AST_MAX_EXTENSION];
1213         /*!
1214          * \brief Voice mailbox location.
1215          * \note Set from the "mailbox" string read in from chan_dahdi.conf
1216          */
1217         char mailbox[AST_MAX_EXTENSION];
1218         /*! \brief Opaque event subscription parameters for message waiting indication support. */
1219         struct ast_event_sub *mwi_event_sub;
1220         /*! \brief Delayed dialing for E911.  Overlap digits for ISDN. */
1221         char dialdest[256];
1222 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
1223         struct dahdi_vmwi_info mwisend_setting;                         /*!< Which VMWI methods to use */
1224         unsigned int mwisend_fsk: 1;            /*! Variable for enabling FSK MWI handling in chan_dahdi */
1225         unsigned int mwisend_rpas:1;            /*! Variable for enabling Ring Pulse Alert before MWI FSK Spill */
1226 #endif
1227         int distinctivering;                            /*!< Which distinctivering to use */
1228         int dtmfrelax;                                  /*!< whether to run in relaxed DTMF mode */
1229         /*! \brief Holding place for event injected from outside normal operation. */
1230         int fake_event;
1231         /*!
1232          * \brief Minimal time period (ms) between the answer polarity
1233          * switch and hangup polarity switch.
1234          */
1235         int polarityonanswerdelay;
1236         /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
1237         struct timeval polaritydelaytv;
1238         /*!
1239          * \brief Send caller ID on FXS after this many rings. Set to 1 for US.
1240          * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
1241          */
1242         int sendcalleridafter;
1243         /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
1244         int polarity;
1245         /*! \brief DSP feature flags: DSP_FEATURE_xxx */
1246         int dsp_features;
1247 #if defined(HAVE_SS7)
1248         /*! \brief SS7 control parameters */
1249         struct sig_ss7_linkset *ss7;
1250 #endif  /* defined(HAVE_SS7) */
1251 #ifdef HAVE_OPENR2
1252         struct dahdi_mfcr2 *mfcr2;
1253         openr2_chan_t *r2chan;
1254         openr2_calling_party_category_t mfcr2_recvd_category;
1255         openr2_calling_party_category_t mfcr2_category;
1256         int mfcr2_dnis_index;
1257         int mfcr2_ani_index;
1258         int mfcr2call:1;
1259         int mfcr2_answer_pending:1;
1260         int mfcr2_charge_calls:1;
1261         int mfcr2_allow_collect_calls:1;
1262         int mfcr2_forced_release:1;
1263         int mfcr2_dnis_matched:1;
1264         int mfcr2_call_accepted:1;
1265         int mfcr2_accept_on_offer:1;
1266         int mfcr2_progress_sent:1;
1267 #endif
1268         /*! \brief DTMF digit in progress.  0 when no digit in progress. */
1269         char begindigit;
1270         /*! \brief TRUE if confrence is muted. */
1271         int muting;
1272         void *sig_pvt;
1273         struct ast_cc_config_params *cc_params;
1274         /* DAHDI channel names may differ greatly from the
1275          * string that was provided to an app such as Dial. We
1276          * need to save the original string passed to dahdi_request
1277          * for call completion purposes. This way, we can replicate
1278          * the original dialed string later.
1279          */
1280         char dialstring[AST_CHANNEL_NAME];
1281 };
1282
1283 #define DATA_EXPORT_DAHDI_PVT(MEMBER)                                   \
1284         MEMBER(dahdi_pvt, cid_rxgain, AST_DATA_DOUBLE)                  \
1285         MEMBER(dahdi_pvt, rxgain, AST_DATA_DOUBLE)                      \
1286         MEMBER(dahdi_pvt, txgain, AST_DATA_DOUBLE)                      \
1287         MEMBER(dahdi_pvt, txdrc, AST_DATA_DOUBLE)                       \
1288         MEMBER(dahdi_pvt, rxdrc, AST_DATA_DOUBLE)                       \
1289         MEMBER(dahdi_pvt, adsi, AST_DATA_BOOLEAN)                       \
1290         MEMBER(dahdi_pvt, answeronpolarityswitch, AST_DATA_BOOLEAN)     \
1291         MEMBER(dahdi_pvt, busydetect, AST_DATA_BOOLEAN)                 \
1292         MEMBER(dahdi_pvt, callreturn, AST_DATA_BOOLEAN)                 \
1293         MEMBER(dahdi_pvt, callwaiting, AST_DATA_BOOLEAN)                \
1294         MEMBER(dahdi_pvt, callwaitingcallerid, AST_DATA_BOOLEAN)        \
1295         MEMBER(dahdi_pvt, cancallforward, AST_DATA_BOOLEAN)             \
1296         MEMBER(dahdi_pvt, canpark, AST_DATA_BOOLEAN)                    \
1297         MEMBER(dahdi_pvt, confirmanswer, AST_DATA_BOOLEAN)              \
1298         MEMBER(dahdi_pvt, destroy, AST_DATA_BOOLEAN)                    \
1299         MEMBER(dahdi_pvt, didtdd, AST_DATA_BOOLEAN)                     \
1300         MEMBER(dahdi_pvt, dialednone, AST_DATA_BOOLEAN)                 \
1301         MEMBER(dahdi_pvt, dialing, AST_DATA_BOOLEAN)                    \
1302         MEMBER(dahdi_pvt, digital, AST_DATA_BOOLEAN)                    \
1303         MEMBER(dahdi_pvt, dnd, AST_DATA_BOOLEAN)                        \
1304         MEMBER(dahdi_pvt, echobreak, AST_DATA_BOOLEAN)                  \
1305         MEMBER(dahdi_pvt, echocanbridged, AST_DATA_BOOLEAN)             \
1306         MEMBER(dahdi_pvt, echocanon, AST_DATA_BOOLEAN)                  \
1307         MEMBER(dahdi_pvt, faxhandled, AST_DATA_BOOLEAN)                 \
1308         MEMBER(dahdi_pvt, usefaxbuffers, AST_DATA_BOOLEAN)              \
1309         MEMBER(dahdi_pvt, bufferoverrideinuse, AST_DATA_BOOLEAN)        \
1310         MEMBER(dahdi_pvt, firstradio, AST_DATA_BOOLEAN)                 \
1311         MEMBER(dahdi_pvt, hanguponpolarityswitch, AST_DATA_BOOLEAN)     \
1312         MEMBER(dahdi_pvt, hardwaredtmf, AST_DATA_BOOLEAN)               \
1313         MEMBER(dahdi_pvt, hidecallerid, AST_DATA_BOOLEAN)               \
1314         MEMBER(dahdi_pvt, hidecalleridname, AST_DATA_BOOLEAN)           \
1315         MEMBER(dahdi_pvt, ignoredtmf, AST_DATA_BOOLEAN)                 \
1316         MEMBER(dahdi_pvt, immediate, AST_DATA_BOOLEAN)                  \
1317         MEMBER(dahdi_pvt, inalarm, AST_DATA_BOOLEAN)                    \
1318         MEMBER(dahdi_pvt, mate, AST_DATA_BOOLEAN)                       \
1319         MEMBER(dahdi_pvt, outgoing, AST_DATA_BOOLEAN)                   \
1320         MEMBER(dahdi_pvt, permcallwaiting, AST_DATA_BOOLEAN)            \
1321         MEMBER(dahdi_pvt, priindication_oob, AST_DATA_BOOLEAN)          \
1322         MEMBER(dahdi_pvt, priexclusive, AST_DATA_BOOLEAN)               \
1323         MEMBER(dahdi_pvt, pulse, AST_DATA_BOOLEAN)                      \
1324         MEMBER(dahdi_pvt, pulsedial, AST_DATA_BOOLEAN)                  \
1325         MEMBER(dahdi_pvt, restartpending, AST_DATA_BOOLEAN)             \
1326         MEMBER(dahdi_pvt, restrictcid, AST_DATA_BOOLEAN)                \
1327         MEMBER(dahdi_pvt, threewaycalling, AST_DATA_BOOLEAN)            \
1328         MEMBER(dahdi_pvt, transfer, AST_DATA_BOOLEAN)                   \
1329         MEMBER(dahdi_pvt, use_callerid, AST_DATA_BOOLEAN)               \
1330         MEMBER(dahdi_pvt, use_callingpres, AST_DATA_BOOLEAN)            \
1331         MEMBER(dahdi_pvt, usedistinctiveringdetection, AST_DATA_BOOLEAN)        \
1332         MEMBER(dahdi_pvt, dahditrcallerid, AST_DATA_BOOLEAN)                    \
1333         MEMBER(dahdi_pvt, transfertobusy, AST_DATA_BOOLEAN)                     \
1334         MEMBER(dahdi_pvt, mwimonitor_neon, AST_DATA_BOOLEAN)                    \
1335         MEMBER(dahdi_pvt, mwimonitor_fsk, AST_DATA_BOOLEAN)                     \
1336         MEMBER(dahdi_pvt, mwimonitor_rpas, AST_DATA_BOOLEAN)                    \
1337         MEMBER(dahdi_pvt, mwimonitoractive, AST_DATA_BOOLEAN)                   \
1338         MEMBER(dahdi_pvt, mwisendactive, AST_DATA_BOOLEAN)                      \
1339         MEMBER(dahdi_pvt, inservice, AST_DATA_BOOLEAN)                          \
1340         MEMBER(dahdi_pvt, locallyblocked, AST_DATA_BOOLEAN)                     \
1341         MEMBER(dahdi_pvt, remotelyblocked, AST_DATA_BOOLEAN)                    \
1342         MEMBER(dahdi_pvt, manages_span_alarms, AST_DATA_BOOLEAN)                \
1343         MEMBER(dahdi_pvt, use_smdi, AST_DATA_BOOLEAN)                           \
1344         MEMBER(dahdi_pvt, context, AST_DATA_STRING)                             \
1345         MEMBER(dahdi_pvt, defcontext, AST_DATA_STRING)                          \
1346         MEMBER(dahdi_pvt, description, AST_DATA_STRING)                         \
1347         MEMBER(dahdi_pvt, exten, AST_DATA_STRING)                               \
1348         MEMBER(dahdi_pvt, language, AST_DATA_STRING)                            \
1349         MEMBER(dahdi_pvt, mohinterpret, AST_DATA_STRING)                        \
1350         MEMBER(dahdi_pvt, mohsuggest, AST_DATA_STRING)                          \
1351         MEMBER(dahdi_pvt, parkinglot, AST_DATA_STRING)
1352
1353 AST_DATA_STRUCTURE(dahdi_pvt, DATA_EXPORT_DAHDI_PVT);
1354
1355 static struct dahdi_pvt *iflist = NULL; /*!< Main interface list start */
1356 static struct dahdi_pvt *ifend = NULL;  /*!< Main interface list end */
1357
1358 #if defined(HAVE_PRI)
1359 static struct dahdi_parms_pseudo {
1360         int buf_no;                                     /*!< Number of buffers */
1361         int buf_policy;                         /*!< Buffer policy */
1362         int faxbuf_no;              /*!< Number of Fax buffers */
1363         int faxbuf_policy;          /*!< Fax buffer policy */
1364 } dahdi_pseudo_parms;
1365 #endif  /* defined(HAVE_PRI) */
1366
1367 /*! \brief Channel configuration from chan_dahdi.conf .
1368  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
1369  * Generally there is a field here for every possible configuration item.
1370  *
1371  * The state of fields is saved along the parsing and whenever a 'channel'
1372  * statement is reached, the current dahdi_chan_conf is used to configure the
1373  * channel (struct dahdi_pvt)
1374  *
1375  * \see dahdi_chan_init for the default values.
1376  */
1377 struct dahdi_chan_conf {
1378         struct dahdi_pvt chan;
1379 #ifdef HAVE_PRI
1380         struct dahdi_pri pri;
1381 #endif
1382
1383 #if defined(HAVE_SS7)
1384         struct dahdi_ss7 ss7;
1385 #endif  /* defined(HAVE_SS7) */
1386
1387 #ifdef HAVE_OPENR2
1388         struct dahdi_mfcr2_conf mfcr2;
1389 #endif
1390         struct dahdi_params timing;
1391         int is_sig_auto; /*!< Use channel signalling from DAHDI? */
1392         /*! Continue configuration even if a channel is not there. */
1393         int ignore_failed_channels;
1394
1395         /*!
1396          * \brief The serial port to listen for SMDI data on
1397          * \note Set from the "smdiport" string read in from chan_dahdi.conf
1398          */
1399         char smdi_port[SMDI_MAX_FILENAME_LEN];
1400 };
1401
1402 /*! returns a new dahdi_chan_conf with default values (by-value) */
1403 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
1404 {
1405         /* recall that if a field is not included here it is initialized
1406          * to 0 or equivalent
1407          */
1408         struct dahdi_chan_conf conf = {
1409 #ifdef HAVE_PRI
1410                 .pri.pri = {
1411                         .nsf = PRI_NSF_NONE,
1412                         .switchtype = PRI_SWITCH_NI2,
1413                         .dialplan = PRI_UNKNOWN + 1,
1414                         .localdialplan = PRI_NATIONAL_ISDN + 1,
1415                         .nodetype = PRI_CPE,
1416                         .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
1417
1418 #if defined(HAVE_PRI_CCSS)
1419                         .cc_ptmp_recall_mode = 1,/* specificRecall */
1420                         .cc_qsig_signaling_link_req = 1,/* retain */
1421                         .cc_qsig_signaling_link_rsp = 1,/* retain */
1422 #endif  /* defined(HAVE_PRI_CCSS) */
1423
1424                         .minunused = 2,
1425                         .idleext = "",
1426                         .idledial = "",
1427                         .internationalprefix = "",
1428                         .nationalprefix = "",
1429                         .localprefix = "",
1430                         .privateprefix = "",
1431                         .unknownprefix = "",
1432                         .colp_send = SIG_PRI_COLP_UPDATE,
1433                         .resetinterval = -1,
1434                 },
1435 #endif
1436 #if defined(HAVE_SS7)
1437                 .ss7.ss7 = {
1438                         .called_nai = SS7_NAI_NATIONAL,
1439                         .calling_nai = SS7_NAI_NATIONAL,
1440                         .internationalprefix = "",
1441                         .nationalprefix = "",
1442                         .subscriberprefix = "",
1443                         .unknownprefix = ""
1444                 },
1445 #endif  /* defined(HAVE_SS7) */
1446 #ifdef HAVE_OPENR2
1447                 .mfcr2 = {
1448                         .variant = OR2_VAR_ITU,
1449                         .mfback_timeout = -1,
1450                         .metering_pulse_timeout = -1,
1451                         .max_ani = 10,
1452                         .max_dnis = 4,
1453                         .get_ani_first = -1,
1454 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
1455                         .skip_category_request = -1,
1456 #endif
1457                         .call_files = 0,
1458                         .allow_collect_calls = 0,
1459                         .charge_calls = 1,
1460                         .accept_on_offer = 1,
1461                         .forced_release = 0,
1462                         .double_answer = 0,
1463                         .immediate_accept = -1,
1464 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 2
1465                         .dtmf_dialing = -1,
1466                         .dtmf_detection = -1,
1467                         .dtmf_time_on = OR2_DEFAULT_DTMF_ON,
1468                         .dtmf_time_off = OR2_DEFAULT_DTMF_OFF,
1469 #endif
1470 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 3
1471                         .dtmf_end_timeout = -1,
1472 #endif
1473                         .logdir = "",
1474                         .r2proto_file = "",
1475                         .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
1476                         .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
1477                 },
1478 #endif
1479                 .chan = {
1480                         .context = "default",
1481                         .cid_num = "",
1482                         .cid_name = "",
1483                         .cid_tag = "",
1484                         .mohinterpret = "default",
1485                         .mohsuggest = "",
1486                         .parkinglot = "",
1487                         .transfertobusy = 1,
1488
1489                         .cid_signalling = CID_SIG_BELL,
1490                         .cid_start = CID_START_RING,
1491                         .dahditrcallerid = 0,
1492                         .use_callerid = 1,
1493                         .sig = -1,
1494                         .outsigmod = -1,
1495
1496                         .cid_rxgain = +5.0,
1497
1498                         .tonezone = -1,
1499
1500                         .echocancel.head.tap_length = 1,
1501
1502                         .busycount = 3,
1503
1504                         .accountcode = "",
1505
1506                         .mailbox = "",
1507
1508 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
1509                         .mwisend_fsk = 1,
1510 #endif
1511                         .polarityonanswerdelay = 600,
1512
1513                         .sendcalleridafter = DEFAULT_CIDRINGS,
1514
1515                         .buf_policy = DAHDI_POLICY_IMMEDIATE,
1516                         .buf_no = numbufs,
1517                         .usefaxbuffers = 0,
1518                         .cc_params = ast_cc_config_params_init(),
1519                 },
1520                 .timing = {
1521                         .prewinktime = -1,
1522                         .preflashtime = -1,
1523                         .winktime = -1,
1524                         .flashtime = -1,
1525                         .starttime = -1,
1526                         .rxwinktime = -1,
1527                         .rxflashtime = -1,
1528                         .debouncetime = -1
1529                 },
1530                 .is_sig_auto = 1,
1531                 .smdi_port = "/dev/ttyS0",
1532         };
1533
1534         return conf;
1535 }
1536
1537
1538 static struct ast_channel *dahdi_request(const char *type, struct ast_format_cap *cap, const struct ast_channel *requestor, const char *data, int *cause);
1539 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
1540 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
1541 static int dahdi_sendtext(struct ast_channel *c, const char *text);
1542 static int dahdi_call(struct ast_channel *ast, const char *rdest, int timeout);
1543 static int dahdi_hangup(struct ast_channel *ast);
1544 static int dahdi_answer(struct ast_channel *ast);
1545 static struct ast_frame *dahdi_read(struct ast_channel *ast);
1546 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
1547 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
1548 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
1549 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1550 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1551 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1552 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
1553 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value);
1554 static int dahdi_devicestate(const char *data);
1555 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback);
1556
1557 static struct ast_channel_tech dahdi_tech = {
1558         .type = "DAHDI",
1559         .description = tdesc,
1560         .requester = dahdi_request,
1561         .send_digit_begin = dahdi_digit_begin,
1562         .send_digit_end = dahdi_digit_end,
1563         .send_text = dahdi_sendtext,
1564         .call = dahdi_call,
1565         .hangup = dahdi_hangup,
1566         .answer = dahdi_answer,
1567         .read = dahdi_read,
1568         .write = dahdi_write,
1569         .bridge = dahdi_bridge,
1570         .exception = dahdi_exception,
1571         .indicate = dahdi_indicate,
1572         .fixup = dahdi_fixup,
1573         .setoption = dahdi_setoption,
1574         .queryoption = dahdi_queryoption,
1575         .func_channel_read = dahdi_func_read,
1576         .func_channel_write = dahdi_func_write,
1577         .devicestate = dahdi_devicestate,
1578         .cc_callback = dahdi_cc_callback,
1579 };
1580
1581 #define GET_CHANNEL(p) ((p)->channel)
1582
1583 #define SIG_PRI_LIB_HANDLE_CASES        \
1584         SIG_PRI:                                                \
1585         case SIG_BRI:                                   \
1586         case SIG_BRI_PTMP
1587
1588 /*!
1589  * \internal
1590  * \brief Determine if sig_pri handles the signaling.
1591  * \since 1.8
1592  *
1593  * \param signaling Signaling to determine if is for sig_pri.
1594  *
1595  * \return TRUE if the signaling is for sig_pri.
1596  */
1597 static inline int dahdi_sig_pri_lib_handles(int signaling)
1598 {
1599         int handles;
1600
1601         switch (signaling) {
1602         case SIG_PRI_LIB_HANDLE_CASES:
1603                 handles = 1;
1604                 break;
1605         default:
1606                 handles = 0;
1607                 break;
1608         }
1609
1610         return handles;
1611 }
1612
1613 static int analog_lib_handles(int signalling, int radio, int oprmode)
1614 {
1615         switch (signalling) {
1616         case SIG_FXOLS:
1617         case SIG_FXOGS:
1618         case SIG_FXOKS:
1619         case SIG_FXSLS:
1620         case SIG_FXSGS:
1621         case SIG_FXSKS:
1622         case SIG_EMWINK:
1623         case SIG_EM:
1624         case SIG_EM_E1:
1625         case SIG_FEATD:
1626         case SIG_FEATDMF:
1627         case SIG_E911:
1628         case SIG_FGC_CAMA:
1629         case SIG_FGC_CAMAMF:
1630         case SIG_FEATB:
1631         case SIG_SFWINK:
1632         case SIG_SF:
1633         case SIG_SF_FEATD:
1634         case SIG_SF_FEATDMF:
1635         case SIG_FEATDMF_TA:
1636         case SIG_SF_FEATB:
1637                 break;
1638         default:
1639                 /* The rest of the function should cover the remainder of signalling types */
1640                 return 0;
1641         }
1642
1643         if (radio) {
1644                 return 0;
1645         }
1646
1647         if (oprmode) {
1648                 return 0;
1649         }
1650
1651         return 1;
1652 }
1653
1654 static enum analog_sigtype dahdisig_to_analogsig(int sig)
1655 {
1656         switch (sig) {
1657         case SIG_FXOLS:
1658                 return ANALOG_SIG_FXOLS;
1659         case SIG_FXOGS:
1660                 return ANALOG_SIG_FXOGS;
1661         case SIG_FXOKS:
1662                 return ANALOG_SIG_FXOKS;
1663         case SIG_FXSLS:
1664                 return ANALOG_SIG_FXSLS;
1665         case SIG_FXSGS:
1666                 return ANALOG_SIG_FXSGS;
1667         case SIG_FXSKS:
1668                 return ANALOG_SIG_FXSKS;
1669         case SIG_EMWINK:
1670                 return ANALOG_SIG_EMWINK;
1671         case SIG_EM:
1672                 return ANALOG_SIG_EM;
1673         case SIG_EM_E1:
1674                 return ANALOG_SIG_EM_E1;
1675         case SIG_FEATD:
1676                 return ANALOG_SIG_FEATD;
1677         case SIG_FEATDMF:
1678                 return ANALOG_SIG_FEATDMF;
1679         case SIG_E911:
1680                 return SIG_E911;
1681         case SIG_FGC_CAMA:
1682                 return ANALOG_SIG_FGC_CAMA;
1683         case SIG_FGC_CAMAMF:
1684                 return ANALOG_SIG_FGC_CAMAMF;
1685         case SIG_FEATB:
1686                 return ANALOG_SIG_FEATB;
1687         case SIG_SFWINK:
1688                 return ANALOG_SIG_SFWINK;
1689         case SIG_SF:
1690                 return ANALOG_SIG_SF;
1691         case SIG_SF_FEATD:
1692                 return ANALOG_SIG_SF_FEATD;
1693         case SIG_SF_FEATDMF:
1694                 return ANALOG_SIG_SF_FEATDMF;
1695         case SIG_FEATDMF_TA:
1696                 return ANALOG_SIG_FEATDMF_TA;
1697         case SIG_SF_FEATB:
1698                 return ANALOG_SIG_FEATB;
1699         default:
1700                 return -1;
1701         }
1702 }
1703
1704
1705 static int analog_tone_to_dahditone(enum analog_tone tone)
1706 {
1707         switch (tone) {
1708         case ANALOG_TONE_RINGTONE:
1709                 return DAHDI_TONE_RINGTONE;
1710         case ANALOG_TONE_STUTTER:
1711                 return DAHDI_TONE_STUTTER;
1712         case ANALOG_TONE_CONGESTION:
1713                 return DAHDI_TONE_CONGESTION;
1714         case ANALOG_TONE_DIALTONE:
1715                 return DAHDI_TONE_DIALTONE;
1716         case ANALOG_TONE_DIALRECALL:
1717                 return DAHDI_TONE_DIALRECALL;
1718         case ANALOG_TONE_INFO:
1719                 return DAHDI_TONE_INFO;
1720         default:
1721                 return -1;
1722         }
1723 }
1724
1725 static int analogsub_to_dahdisub(enum analog_sub analogsub)
1726 {
1727         int index;
1728
1729         switch (analogsub) {
1730         case ANALOG_SUB_REAL:
1731                 index = SUB_REAL;
1732                 break;
1733         case ANALOG_SUB_CALLWAIT:
1734                 index = SUB_CALLWAIT;
1735                 break;
1736         case ANALOG_SUB_THREEWAY:
1737                 index = SUB_THREEWAY;
1738                 break;
1739         default:
1740                 ast_log(LOG_ERROR, "Unidentified sub!\n");
1741                 index = SUB_REAL;
1742         }
1743
1744         return index;
1745 }
1746
1747 /*!
1748  * \internal
1749  * \brief Send a dial string to DAHDI.
1750  * \since 12.0.0
1751  *
1752  * \param pvt DAHDI private pointer
1753  * \param operation DAHDI dial operation to do to string
1754  * \param dial_str Dial string to send
1755  *
1756  * \retval 0 on success.
1757  * \retval non-zero on error.
1758  */
1759 static int dahdi_dial_str(struct dahdi_pvt *pvt, int operation, const char *dial_str)
1760 {
1761         int res;
1762         int offset;
1763         const char *pos;
1764         struct dahdi_dialoperation zo = {
1765                 .op = operation,
1766         };
1767
1768         /* Convert the W's to ww. */
1769         pos = dial_str;
1770         for (offset = 0; offset < sizeof(zo.dialstr) - 1; ++offset) {
1771                 if (!*pos) {
1772                         break;
1773                 }
1774                 if (*pos == 'W') {
1775                         /* Convert 'W' to "ww" */
1776                         ++pos;
1777                         if (offset >= sizeof(zo.dialstr) - 3) {
1778                                 /* No room to expand */
1779                                 break;
1780                         }
1781                         zo.dialstr[offset] = 'w';
1782                         ++offset;
1783                         zo.dialstr[offset] = 'w';
1784                         continue;
1785                 }
1786                 zo.dialstr[offset] = *pos++;
1787         }
1788         /* The zo initialization has already terminated the dialstr. */
1789
1790         ast_debug(1, "Channel %d: Dial str '%s' expanded to '%s' sent to DAHDI_DIAL.\n",
1791                 pvt->channel, dial_str, zo.dialstr);
1792         res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo);
1793         if (res) {
1794                 ast_log(LOG_WARNING, "Channel %d: Couldn't dial '%s': %s\n",
1795                         pvt->channel, dial_str, strerror(errno));
1796         }
1797
1798         return res;
1799 }
1800
1801 static enum analog_event dahdievent_to_analogevent(int event);
1802 static int bump_gains(struct dahdi_pvt *p);
1803 static int dahdi_setlinear(int dfd, int linear);
1804
1805 static int my_start_cid_detect(void *pvt, int cid_signalling)
1806 {
1807         struct dahdi_pvt *p = pvt;
1808         int index = SUB_REAL;
1809         p->cs = callerid_new(cid_signalling);
1810         if (!p->cs) {
1811                 ast_log(LOG_ERROR, "Unable to alloc callerid\n");
1812                 return -1;
1813         }
1814         bump_gains(p);
1815         dahdi_setlinear(p->subs[index].dfd, 0);
1816
1817         return 0;
1818 }
1819
1820 static int my_stop_cid_detect(void *pvt)
1821 {
1822         struct dahdi_pvt *p = pvt;
1823         int index = SUB_REAL;
1824         if (p->cs)
1825                 callerid_free(p->cs);
1826         dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
1827         return 0;
1828 }
1829
1830 static int my_get_callerid(void *pvt, char *namebuf, char *numbuf, enum analog_event *ev, size_t timeout)
1831 {
1832         struct dahdi_pvt *p = pvt;
1833         struct analog_pvt *analog_p = p->sig_pvt;
1834         struct pollfd poller;
1835         char *name, *num;
1836         int index = SUB_REAL;
1837         int res;
1838         unsigned char buf[256];
1839         int flags;
1840         struct ast_format tmpfmt;
1841
1842         poller.fd = p->subs[SUB_REAL].dfd;
1843         poller.events = POLLPRI | POLLIN;
1844         poller.revents = 0;
1845
1846         res = poll(&poller, 1, timeout);
1847
1848         if (poller.revents & POLLPRI) {
1849                 *ev = dahdievent_to_analogevent(dahdi_get_event(p->subs[SUB_REAL].dfd));
1850                 return 1;
1851         }
1852
1853         if (poller.revents & POLLIN) {
1854                 /*** NOTES ***/
1855                 /* Change API: remove cid_signalling from get_callerid, add a new start_cid_detect and stop_cid_detect function
1856                  * to enable slin mode and allocate cid detector. get_callerid should be able to be called any number of times until
1857                  * either a timeout occurs or CID is detected (returns 0). returning 1 should be event received, and -1 should be
1858                  * a failure and die, and returning 2 means no event was received. */
1859                 res = read(p->subs[index].dfd, buf, sizeof(buf));
1860                 if (res < 0) {
1861                         if (errno != ELAST) {
1862                                 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
1863                                 callerid_free(p->cs);
1864                                 return -1;
1865                         }
1866                 }
1867
1868                 if (analog_p->ringt > 0) {
1869                         if (!(--analog_p->ringt)) {
1870                                 /* only return if we timeout from a ring event */
1871                                 return -1;
1872                         }
1873                 }
1874
1875                 if (p->cid_signalling == CID_SIG_V23_JP) {
1876                         res = callerid_feed_jp(p->cs, buf, res, ast_format_set(&tmpfmt, AST_LAW(p), 0));
1877                 } else {
1878                         res = callerid_feed(p->cs, buf, res, ast_format_set(&tmpfmt, AST_LAW(p), 0));
1879                 }
1880                 if (res < 0) {
1881                         /*
1882                          * The previous diagnostic message output likely
1883                          * explains why it failed.
1884                          */
1885                         ast_log(LOG_WARNING, "Failed to decode CallerID\n");
1886                         return -1;
1887                 }
1888
1889                 if (res == 1) {
1890                         callerid_get(p->cs, &name, &num, &flags);
1891                         if (name)
1892                                 ast_copy_string(namebuf, name, ANALOG_MAX_CID);
1893                         if (num)
1894                                 ast_copy_string(numbuf, num, ANALOG_MAX_CID);
1895
1896                         ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", num, name, flags);
1897                         return 0;
1898                 }
1899         }
1900
1901         *ev = ANALOG_EVENT_NONE;
1902         return 2;
1903 }
1904
1905 static const char *event2str(int event);
1906 static int restore_gains(struct dahdi_pvt *p);
1907
1908 static int my_distinctive_ring(struct ast_channel *chan, void *pvt, int idx, int *ringdata)
1909 {
1910         unsigned char buf[256];
1911         int distMatches;
1912         int curRingData[RING_PATTERNS];
1913         int receivedRingT;
1914         int counter1;
1915         int counter;
1916         int i;
1917         int res;
1918         int checkaftercid = 0;
1919
1920         struct dahdi_pvt *p = pvt;
1921         struct analog_pvt *analog_p = p->sig_pvt;
1922
1923         if (ringdata == NULL) {
1924                 ringdata = curRingData;
1925         } else {
1926                 checkaftercid = 1;
1927         }
1928
1929         /* We must have a ring by now, so, if configured, lets try to listen for
1930          * distinctive ringing */
1931         if ((checkaftercid && distinctiveringaftercid) || !checkaftercid) {
1932                 /* Clear the current ring data array so we don't have old data in it. */
1933                 for (receivedRingT = 0; receivedRingT < RING_PATTERNS; receivedRingT++)
1934                         ringdata[receivedRingT] = 0;
1935                 receivedRingT = 0;
1936                 if (checkaftercid && distinctiveringaftercid)
1937                         ast_verb(3, "Detecting post-CID distinctive ring\n");
1938                 /* Check to see if context is what it should be, if not set to be. */
1939                 else if (strcmp(p->context,p->defcontext) != 0) {
1940                         ast_copy_string(p->context, p->defcontext, sizeof(p->context));
1941                         ast_channel_context_set(chan, p->defcontext);
1942                 }
1943
1944                 for (;;) {
1945                         i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
1946                         if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
1947                                 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
1948                                 ast_hangup(chan);
1949                                 return 1;
1950                         }
1951                         if (i & DAHDI_IOMUX_SIGEVENT) {
1952                                 res = dahdi_get_event(p->subs[idx].dfd);
1953                                 if (res == DAHDI_EVENT_NOALARM) {
1954                                         p->inalarm = 0;
1955                                         analog_p->inalarm = 0;
1956                                 }
1957                                 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
1958                                 res = 0;
1959                                 /* Let us detect distinctive ring */
1960
1961                                 ringdata[receivedRingT] = analog_p->ringt;
1962
1963                                 if (analog_p->ringt < analog_p->ringt_base/2)
1964                                         break;
1965                                 /* Increment the ringT counter so we can match it against
1966                                    values in chan_dahdi.conf for distinctive ring */
1967                                 if (++receivedRingT == RING_PATTERNS)
1968                                         break;
1969                         } else if (i & DAHDI_IOMUX_READ) {
1970                                 res = read(p->subs[idx].dfd, buf, sizeof(buf));
1971                                 if (res < 0) {
1972                                         if (errno != ELAST) {
1973                                                 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
1974                                                 ast_hangup(chan);
1975                                                 return 1;
1976                                         }
1977                                         break;
1978                                 }
1979                                 if (analog_p->ringt > 0) {
1980                                         if (!(--analog_p->ringt)) {
1981                                                 res = -1;
1982                                                 break;
1983                                         }
1984                                 }
1985                         }
1986                 }
1987         }
1988         if ((checkaftercid && usedistinctiveringdetection) || !checkaftercid) {
1989                 /* this only shows up if you have n of the dring patterns filled in */
1990                 ast_verb(3, "Detected ring pattern: %d,%d,%d\n",ringdata[0],ringdata[1],ringdata[2]);
1991                 for (counter = 0; counter < 3; counter++) {
1992                 /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this channel */
1993                         distMatches = 0;
1994                         /* this only shows up if you have n of the dring patterns filled in */
1995                         ast_verb(3, "Checking %d,%d,%d\n",
1996                                         p->drings.ringnum[counter].ring[0],
1997                                         p->drings.ringnum[counter].ring[1],
1998                                         p->drings.ringnum[counter].ring[2]);
1999                         for (counter1 = 0; counter1 < 3; counter1++) {
2000                                 ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
2001                                 if (p->drings.ringnum[counter].ring[counter1] == -1) {
2002                                         ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
2003                                         ringdata[counter1]);
2004                                         distMatches++;
2005                                 } else if (ringdata[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
2006                                                                                 ringdata[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
2007                                         ast_verb(3, "Ring pattern matched in range: %d to %d\n",
2008                                         (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
2009                                         (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
2010                                         distMatches++;
2011                                 }
2012                         }
2013
2014                         if (distMatches == 3) {
2015                                 /* The ring matches, set the context to whatever is for distinctive ring.. */
2016                                 ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
2017                                 ast_channel_context_set(chan, S_OR(p->drings.ringContext[counter].contextData, p->defcontext));
2018                                 ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
2019                                 break;
2020                         }
2021                 }
2022         }
2023         /* Restore linear mode (if appropriate) for Caller*ID processing */
2024         dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
2025         restore_gains(p);
2026
2027         return 0;
2028 }
2029
2030 static int my_stop_callwait(void *pvt)
2031 {
2032         struct dahdi_pvt *p = pvt;
2033         p->callwaitingrepeat = 0;
2034         p->cidcwexpire = 0;
2035         p->cid_suppress_expire = 0;
2036
2037         return 0;
2038 }
2039
2040 static int send_callerid(struct dahdi_pvt *p);
2041 static int save_conference(struct dahdi_pvt *p);
2042 static int restore_conference(struct dahdi_pvt *p);
2043
2044 static int my_callwait(void *pvt)
2045 {
2046         struct dahdi_pvt *p = pvt;
2047         struct ast_format tmpfmt;
2048         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
2049         if (p->cidspill) {
2050                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
2051                 ast_free(p->cidspill);
2052         }
2053
2054         /*
2055          * SAS: Subscriber Alert Signal, 440Hz for 300ms
2056          * CAS: CPE Alert Signal, 2130Hz * 2750Hz sine waves
2057          */
2058         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
2059                 return -1;
2060         save_conference(p);
2061         /* Silence */
2062         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
2063         if (!p->callwaitrings && p->callwaitingcallerid) {
2064                 ast_gen_cas(p->cidspill, 1, 2400 + 680, ast_format_set(&tmpfmt, AST_LAW(p), 0));
2065                 p->callwaitcas = 1;
2066                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
2067         } else {
2068                 ast_gen_cas(p->cidspill, 1, 2400, ast_format_set(&tmpfmt, AST_LAW(p), 0));
2069                 p->callwaitcas = 0;
2070                 p->cidlen = 2400 + READ_SIZE * 4;
2071         }
2072         p->cidpos = 0;
2073         send_callerid(p);
2074
2075         return 0;
2076 }
2077
2078 static int my_send_callerid(void *pvt, int cwcid, struct ast_party_caller *caller)
2079 {
2080         struct dahdi_pvt *p = pvt;
2081         struct ast_format tmpfmt;
2082
2083         ast_debug(2, "Starting cid spill\n");
2084
2085         if (p->cidspill) {
2086                 ast_log(LOG_WARNING, "cidspill already exists??\n");
2087                 ast_free(p->cidspill);
2088         }
2089
2090         if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
2091                 if (cwcid == 0) {
2092                         p->cidlen = ast_callerid_generate(p->cidspill,
2093                                 caller->id.name.str,
2094                                 caller->id.number.str,
2095                                 ast_format_set(&tmpfmt, AST_LAW(p), 0));
2096                 } else {
2097                         ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n",
2098                                 caller->id.name.str, caller->id.number.str);
2099                         p->callwaitcas = 0;
2100                         p->cidcwexpire = 0;
2101                         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill,
2102                                 caller->id.name.str,
2103                                 caller->id.number.str,
2104                                 ast_format_set(&tmpfmt, AST_LAW(p), 0));
2105                         p->cidlen += READ_SIZE * 4;
2106                 }
2107                 p->cidpos = 0;
2108                 p->cid_suppress_expire = 0;
2109                 send_callerid(p);
2110         }
2111         return 0;
2112 }
2113
2114 static int my_dsp_reset_and_flush_digits(void *pvt)
2115 {
2116         struct dahdi_pvt *p = pvt;
2117         if (p->dsp)
2118                 ast_dsp_digitreset(p->dsp);
2119
2120         return 0;
2121 }
2122
2123 static int my_dsp_set_digitmode(void *pvt, enum analog_dsp_digitmode mode)
2124 {
2125         struct dahdi_pvt *p = pvt;
2126
2127         if (p->channel == CHAN_PSEUDO)
2128                 ast_log(LOG_ERROR, "You have assumed incorrectly sir!\n");
2129
2130         if (mode == ANALOG_DIGITMODE_DTMF) {
2131                 /* If we do hardware dtmf, no need for a DSP */
2132                 if (p->hardwaredtmf) {
2133                         if (p->dsp) {
2134                                 ast_dsp_free(p->dsp);
2135                                 p->dsp = NULL;
2136                         }
2137                         return 0;
2138                 }
2139
2140                 if (!p->dsp) {
2141                         p->dsp = ast_dsp_new();
2142                         if (!p->dsp) {
2143                                 ast_log(LOG_ERROR, "Unable to allocate DSP\n");
2144                                 return -1;
2145                         }
2146                 }
2147
2148                 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
2149         } else if (mode == ANALOG_DIGITMODE_MF) {
2150                 if (!p->dsp) {
2151                         p->dsp = ast_dsp_new();
2152                         if (!p->dsp) {
2153                                 ast_log(LOG_ERROR, "Unable to allocate DSP\n");
2154                                 return -1;
2155                         }
2156                 }
2157                 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
2158         }
2159         return 0;
2160 }
2161
2162 static int dahdi_wink(struct dahdi_pvt *p, int index);
2163
2164 static int my_wink(void *pvt, enum analog_sub sub)
2165 {
2166         struct dahdi_pvt *p = pvt;
2167         int index = analogsub_to_dahdisub(sub);
2168         if (index != SUB_REAL) {
2169                 ast_log(LOG_ERROR, "We used a sub other than SUB_REAL (incorrect assumption sir)\n");
2170         }
2171         return dahdi_wink(p, index);
2172 }
2173
2174 static void wakeup_sub(struct dahdi_pvt *p, int a);
2175
2176 static int reset_conf(struct dahdi_pvt *p);
2177
2178 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted);
2179
2180 static void my_handle_dtmf(void *pvt, struct ast_channel *ast, enum analog_sub analog_index, struct ast_frame **dest)
2181 {
2182         struct ast_frame *f = *dest;
2183         struct dahdi_pvt *p = pvt;
2184         int idx = analogsub_to_dahdisub(analog_index);
2185
2186         ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
2187                 f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
2188                 f->subclass.integer, f->subclass.integer, ast_channel_name(ast));
2189
2190         if (f->subclass.integer == 'f') {
2191                 if (f->frametype == AST_FRAME_DTMF_END) {
2192                         /* Fax tone -- Handle and return NULL */
2193                         if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
2194                                 /* If faxbuffers are configured, use them for the fax transmission */
2195                                 if (p->usefaxbuffers && !p->bufferoverrideinuse) {
2196                                         struct dahdi_bufferinfo bi = {
2197                                                 .txbufpolicy = p->faxbuf_policy,
2198                                                 .bufsize = p->bufsize,
2199                                                 .numbufs = p->faxbuf_no
2200                                         };
2201                                         int res;
2202
2203                                         if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
2204                                                 ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast_channel_name(ast), strerror(errno));
2205                                         } else {
2206                                                 p->bufferoverrideinuse = 1;
2207                                         }
2208                                 }
2209                                 p->faxhandled = 1;
2210                                 if (p->dsp) {
2211                                         p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
2212                                         ast_dsp_set_features(p->dsp, p->dsp_features);
2213                                         ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast_channel_name(ast));
2214                                 }
2215                                 if (strcmp(ast_channel_exten(ast), "fax")) {
2216                                         const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
2217
2218                                         /* We need to unlock 'ast' here because ast_exists_extension has the
2219                                          * potential to start autoservice on the channel. Such action is prone
2220                                          * to deadlock.
2221                                          */
2222                                         ast_mutex_unlock(&p->lock);
2223                                         ast_channel_unlock(ast);
2224                                         if (ast_exists_extension(ast, target_context, "fax", 1,
2225                                                 S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
2226                                                 ast_channel_lock(ast);
2227                                                 ast_mutex_lock(&p->lock);
2228                                                 ast_verb(3, "Redirecting %s to fax extension\n", ast_channel_name(ast));
2229                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
2230                                                 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
2231                                                 if (ast_async_goto(ast, target_context, "fax", 1))
2232                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
2233                                         } else {
2234                                                 ast_channel_lock(ast);
2235                                                 ast_mutex_lock(&p->lock);
2236                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
2237                                         }
2238                                 } else {
2239                                         ast_debug(1, "Already in a fax extension, not redirecting\n");
2240                                 }
2241                         } else {
2242                                 ast_debug(1, "Fax already handled\n");
2243                         }
2244                         dahdi_confmute(p, 0);
2245                 }
2246                 p->subs[idx].f.frametype = AST_FRAME_NULL;
2247                 p->subs[idx].f.subclass.integer = 0;
2248                 *dest = &p->subs[idx].f;
2249         }
2250 }
2251
2252 static void my_lock_private(void *pvt)
2253 {
2254         struct dahdi_pvt *p = pvt;
2255         ast_mutex_lock(&p->lock);
2256 }
2257
2258 static void my_unlock_private(void *pvt)
2259 {
2260         struct dahdi_pvt *p = pvt;
2261         ast_mutex_unlock(&p->lock);
2262 }
2263
2264 static void my_deadlock_avoidance_private(void *pvt)
2265 {
2266         struct dahdi_pvt *p = pvt;
2267
2268         DEADLOCK_AVOIDANCE(&p->lock);
2269 }
2270
2271 /*!
2272  * \internal
2273  * \brief Post an AMI DAHDI channel association event.
2274  * \since 1.8
2275  *
2276  * \param p DAHDI private pointer
2277  * \param chan Channel associated with the private pointer
2278  *
2279  * \return Nothing
2280  */
2281 static void dahdi_ami_channel_event(struct dahdi_pvt *p, struct ast_channel *chan)
2282 {
2283         char ch_name[20];
2284
2285         if (p->channel < CHAN_PSEUDO) {
2286                 /* No B channel */
2287                 snprintf(ch_name, sizeof(ch_name), "no-media (%d)", p->channel);
2288         } else if (p->channel == CHAN_PSEUDO) {
2289                 /* Pseudo channel */
2290                 strcpy(ch_name, "pseudo");
2291         } else {
2292                 /* Real channel */
2293                 snprintf(ch_name, sizeof(ch_name), "%d", p->channel);
2294         }
2295         /*** DOCUMENTATION
2296                 <managerEventInstance>
2297                         <synopsis>Raised when a DAHDI channel is created or an underlying technology is associated with a DAHDI channel.</synopsis>
2298                 </managerEventInstance>
2299         ***/
2300         ast_manager_event(chan, EVENT_FLAG_CALL, "DAHDIChannel",
2301                 "Channel: %s\r\n"
2302                 "Uniqueid: %s\r\n"
2303                 "DAHDISpan: %d\r\n"
2304                 "DAHDIChannel: %s\r\n",
2305                 ast_channel_name(chan),
2306                 ast_channel_uniqueid(chan),
2307                 p->span,
2308                 ch_name);
2309 }
2310
2311 #ifdef HAVE_PRI
2312 /*!
2313  * \internal
2314  * \brief Post an AMI DAHDI channel association event.
2315  * \since 1.8
2316  *
2317  * \param pvt DAHDI private pointer
2318  * \param chan Channel associated with the private pointer
2319  *
2320  * \return Nothing
2321  */
2322 static void my_ami_channel_event(void *pvt, struct ast_channel *chan)
2323 {
2324         struct dahdi_pvt *p = pvt;
2325
2326         dahdi_ami_channel_event(p, chan);
2327 }
2328 #endif
2329
2330 /* linear_mode = 0 - turn linear mode off, >0 - turn linear mode on
2331 *       returns the last value of the linear setting 
2332 */ 
2333 static int my_set_linear_mode(void *pvt, enum analog_sub sub, int linear_mode)
2334 {
2335         struct dahdi_pvt *p = pvt;
2336         int oldval;
2337         int idx = analogsub_to_dahdisub(sub);
2338         
2339         dahdi_setlinear(p->subs[idx].dfd, linear_mode);
2340         oldval = p->subs[idx].linear;
2341         p->subs[idx].linear = linear_mode ? 1 : 0;
2342         return oldval;
2343 }
2344
2345 static void my_set_inthreeway(void *pvt, enum analog_sub sub, int inthreeway)
2346 {
2347         struct dahdi_pvt *p = pvt;
2348         int idx = analogsub_to_dahdisub(sub);
2349
2350         p->subs[idx].inthreeway = inthreeway;
2351 }
2352
2353 static int get_alarms(struct dahdi_pvt *p);
2354 static void handle_alarms(struct dahdi_pvt *p, int alms);
2355 static void my_get_and_handle_alarms(void *pvt)
2356 {
2357         int res;
2358         struct dahdi_pvt *p = pvt;
2359
2360         res = get_alarms(p);
2361         handle_alarms(p, res);
2362 }
2363
2364 static void *my_get_sigpvt_bridged_channel(struct ast_channel *chan)
2365 {
2366         struct ast_channel *bridged = ast_bridged_channel(chan);
2367
2368         if (bridged && ast_channel_tech(bridged) == &dahdi_tech) {
2369                 struct dahdi_pvt *p = ast_channel_tech_pvt(bridged);
2370
2371                 if (analog_lib_handles(p->sig, p->radio, p->oprmode)) {
2372                         return p->sig_pvt;
2373                 }
2374         }
2375         return NULL;
2376 }
2377
2378 static int my_get_sub_fd(void *pvt, enum analog_sub sub)
2379 {
2380         struct dahdi_pvt *p = pvt;
2381         int dahdi_sub = analogsub_to_dahdisub(sub);
2382         return p->subs[dahdi_sub].dfd;
2383 }
2384
2385 static void my_set_cadence(void *pvt, int *cid_rings, struct ast_channel *ast)
2386 {
2387         struct dahdi_pvt *p = pvt;
2388
2389         /* Choose proper cadence */
2390         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
2391                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
2392                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast_channel_name(ast), strerror(errno));
2393                 *cid_rings = cidrings[p->distinctivering - 1];
2394         } else {
2395                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
2396                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast_channel_name(ast), strerror(errno));
2397                 *cid_rings = p->sendcalleridafter;
2398         }
2399 }
2400
2401 static void my_set_alarm(void *pvt, int in_alarm)
2402 {
2403         struct dahdi_pvt *p = pvt;
2404
2405         p->inalarm = in_alarm;
2406 }
2407
2408 static void my_set_dialing(void *pvt, int is_dialing)
2409 {
2410         struct dahdi_pvt *p = pvt;
2411
2412         p->dialing = is_dialing;
2413 }
2414
2415 static void my_set_outgoing(void *pvt, int is_outgoing)
2416 {
2417         struct dahdi_pvt *p = pvt;
2418
2419         p->outgoing = is_outgoing;
2420 }
2421
2422 #if defined(HAVE_PRI) || defined(HAVE_SS7)
2423 static void my_set_digital(void *pvt, int is_digital)
2424 {
2425         struct dahdi_pvt *p = pvt;
2426
2427         p->digital = is_digital;
2428 }
2429 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
2430
2431 #if defined(HAVE_SS7)
2432 static void my_set_inservice(void *pvt, int is_inservice)
2433 {
2434         struct dahdi_pvt *p = pvt;
2435
2436         p->inservice = is_inservice;
2437 }
2438 #endif  /* defined(HAVE_SS7) */
2439
2440 #if defined(HAVE_SS7)
2441 static void my_set_locallyblocked(void *pvt, int is_blocked)
2442 {
2443         struct dahdi_pvt *p = pvt;
2444
2445         p->locallyblocked = is_blocked;
2446 }
2447 #endif  /* defined(HAVE_SS7) */
2448
2449 #if defined(HAVE_SS7)
2450 static void my_set_remotelyblocked(void *pvt, int is_blocked)
2451 {
2452         struct dahdi_pvt *p = pvt;
2453
2454         p->remotelyblocked = is_blocked;
2455 }
2456 #endif  /* defined(HAVE_SS7) */
2457
2458 static void my_set_ringtimeout(void *pvt, int ringt)
2459 {
2460         struct dahdi_pvt *p = pvt;
2461         p->ringt = ringt;
2462 }
2463
2464 static void my_set_waitingfordt(void *pvt, struct ast_channel *ast)
2465 {
2466         struct dahdi_pvt *p = pvt;
2467
2468         if (p->waitfordialtone && CANPROGRESSDETECT(p) && p->dsp) {
2469                 ast_debug(1, "Defer dialing for %dms or dialtone\n", p->waitfordialtone);
2470                 gettimeofday(&p->waitingfordt, NULL);
2471                 ast_setstate(ast, AST_STATE_OFFHOOK);
2472         }
2473 }
2474
2475 static int my_check_waitingfordt(void *pvt)
2476 {
2477         struct dahdi_pvt *p = pvt;
2478
2479         if (p->waitingfordt.tv_usec) {
2480                 return 1;
2481         }
2482
2483         return 0;
2484 }
2485
2486 static void my_set_confirmanswer(void *pvt, int flag)
2487 {
2488         struct dahdi_pvt *p = pvt;
2489         p->confirmanswer = flag;
2490 }
2491
2492 static int my_check_confirmanswer(void *pvt)
2493 {
2494         struct dahdi_pvt *p = pvt;
2495         if (p->confirmanswer) {
2496                 return 1;
2497         }
2498
2499         return 0;
2500 }
2501
2502 static void my_set_callwaiting(void *pvt, int callwaiting_enable)
2503 {
2504         struct dahdi_pvt *p = pvt;
2505
2506         p->callwaiting = callwaiting_enable;
2507 }
2508
2509 static void my_cancel_cidspill(void *pvt)
2510 {
2511         struct dahdi_pvt *p = pvt;
2512
2513         ast_free(p->cidspill);
2514         p->cidspill = NULL;
2515         restore_conference(p);
2516 }
2517
2518 static int my_confmute(void *pvt, int mute)
2519 {
2520         struct dahdi_pvt *p = pvt;
2521         return dahdi_confmute(p, mute);
2522 }
2523
2524 static void my_set_pulsedial(void *pvt, int flag)
2525 {
2526         struct dahdi_pvt *p = pvt;
2527         p->pulsedial = flag;
2528 }
2529
2530 static void my_set_new_owner(void *pvt, struct ast_channel *new_owner)
2531 {
2532         struct dahdi_pvt *p = pvt;
2533
2534         p->owner = new_owner;
2535 }
2536
2537 static const char *my_get_orig_dialstring(void *pvt)
2538 {
2539         struct dahdi_pvt *p = pvt;
2540
2541         return p->dialstring;
2542 }
2543
2544 static void my_increase_ss_count(void)
2545 {
2546         ast_mutex_lock(&ss_thread_lock);
2547         ss_thread_count++;
2548         ast_mutex_unlock(&ss_thread_lock);
2549 }
2550
2551 static void my_decrease_ss_count(void)
2552 {
2553         ast_mutex_lock(&ss_thread_lock);
2554         ss_thread_count--;
2555         ast_cond_signal(&ss_thread_complete);
2556         ast_mutex_unlock(&ss_thread_lock);
2557 }
2558
2559 static void my_all_subchannels_hungup(void *pvt)
2560 {
2561         struct dahdi_pvt *p = pvt;
2562         int res, law;
2563
2564         p->faxhandled = 0;
2565         p->didtdd = 0;
2566
2567         if (p->dsp) {
2568                 ast_dsp_free(p->dsp);
2569                 p->dsp = NULL;
2570         }
2571
2572         p->law = p->law_default;
2573         law = p->law_default;
2574         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
2575         if (res < 0)
2576                 ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
2577
2578         dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
2579
2580 #if 1
2581         {
2582         int i;
2583         p->owner = NULL;
2584         /* Cleanup owners here */
2585         for (i = 0; i < 3; i++) {
2586                 p->subs[i].owner = NULL;
2587         }
2588         }
2589 #endif
2590
2591         reset_conf(p);
2592         if (num_restart_pending == 0) {
2593                 restart_monitor();
2594         }
2595 }
2596
2597 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index);
2598
2599 static int my_conf_del(void *pvt, enum analog_sub sub)
2600 {
2601         struct dahdi_pvt *p = pvt;
2602         int x = analogsub_to_dahdisub(sub);
2603
2604         return conf_del(p, &p->subs[x], x);
2605 }
2606
2607 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index, int slavechannel);
2608
2609 static int my_conf_add(void *pvt, enum analog_sub sub)
2610 {
2611         struct dahdi_pvt *p = pvt;
2612         int x = analogsub_to_dahdisub(sub);
2613
2614         return conf_add(p, &p->subs[x], x, 0);
2615 }
2616
2617 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out);
2618
2619 static int my_complete_conference_update(void *pvt, int needconference)
2620 {
2621         struct dahdi_pvt *p = pvt;
2622         int needconf = needconference;
2623         int x;
2624         int useslavenative;
2625         struct dahdi_pvt *slave = NULL;
2626
2627         useslavenative = isslavenative(p, &slave);
2628
2629         /* If we have a slave, add him to our conference now. or DAX
2630            if this is slave native */
2631         for (x = 0; x < MAX_SLAVES; x++) {
2632                 if (p->slaves[x]) {
2633                         if (useslavenative)
2634                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
2635                         else {
2636                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
2637                                 needconf++;
2638                         }
2639                 }
2640         }
2641         /* If we're supposed to be in there, do so now */
2642         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
2643                 if (useslavenative)
2644                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
2645                 else {
2646                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
2647                         needconf++;
2648                 }
2649         }
2650         /* If we have a master, add ourselves to his conference */
2651         if (p->master) {
2652                 if (isslavenative(p->master, NULL)) {
2653                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
2654                 } else {
2655                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
2656                 }
2657         }
2658         if (!needconf) {
2659                 /* Nobody is left (or should be left) in our conference.
2660                    Kill it. */
2661                 p->confno = -1;
2662         }
2663
2664         return 0;
2665 }
2666
2667 static int check_for_conference(struct dahdi_pvt *p);
2668
2669 static int my_check_for_conference(void *pvt)
2670 {
2671         struct dahdi_pvt *p = pvt;
2672         return check_for_conference(p);
2673 }
2674
2675 static void my_swap_subchannels(void *pvt, enum analog_sub a, struct ast_channel *ast_a,  enum analog_sub b, struct ast_channel *ast_b)
2676 {
2677         struct dahdi_pvt *p = pvt;
2678         int da, db;
2679         int tchan;
2680         int tinthreeway;
2681
2682         da = analogsub_to_dahdisub(a);
2683         db = analogsub_to_dahdisub(b);
2684
2685         tchan = p->subs[da].chan;
2686         p->subs[da].chan = p->subs[db].chan;
2687         p->subs[db].chan = tchan;
2688
2689         tinthreeway = p->subs[da].inthreeway;
2690         p->subs[da].inthreeway = p->subs[db].inthreeway;
2691         p->subs[db].inthreeway = tinthreeway;
2692
2693         p->subs[da].owner = ast_a;
2694         p->subs[db].owner = ast_b;
2695
2696         if (ast_a)
2697                 ast_channel_set_fd(ast_a, 0, p->subs[da].dfd);
2698         if (ast_b)
2699                 ast_channel_set_fd(ast_b, 0, p->subs[db].dfd);
2700
2701         wakeup_sub(p, a);
2702         wakeup_sub(p, b);
2703
2704         return;
2705 }
2706
2707 /*!
2708  * \internal
2709  * \brief performs duties of dahdi_new, but also removes and possibly unbinds (if callid_created is 1) before returning
2710  * \note this variant of dahdi should only be used in conjunction with ast_callid_threadstorage_auto()
2711  *
2712  * \param callid_created value returned from ast_callid_threadstorage_auto()
2713  */
2714 static struct ast_channel *dahdi_new_callid_clean(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linked, struct ast_callid *callid, int callid_created);
2715
2716 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const char *linkedid, struct ast_callid *callid);
2717
2718 static struct ast_channel *my_new_analog_ast_channel(void *pvt, int state, int startpbx, enum analog_sub sub, const struct ast_channel *requestor)
2719 {
2720         struct ast_callid *callid = NULL;
2721         int callid_created = ast_callid_threadstorage_auto(&callid);
2722         struct dahdi_pvt *p = pvt;
2723         int dsub = analogsub_to_dahdisub(sub);
2724
2725         return dahdi_new_callid_clean(p, state, startpbx, dsub, 0, requestor ? ast_channel_linkedid(requestor) : "", callid, callid_created);
2726 }
2727
2728 #if defined(HAVE_PRI) || defined(HAVE_SS7)
2729 static int dahdi_setlaw(int dfd, int law)
2730 {
2731         int res;
2732         res = ioctl(dfd, DAHDI_SETLAW, &law);
2733         if (res)
2734                 return res;
2735         return 0;
2736 }
2737 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
2738
2739 #if defined(HAVE_PRI)
2740 static struct ast_channel *my_new_pri_ast_channel(void *pvt, int state, enum sig_pri_law law, char *exten, const struct ast_channel *requestor)
2741 {
2742         struct dahdi_pvt *p = pvt;
2743         int audio;
2744         int newlaw = -1;
2745         struct ast_callid *callid = NULL;
2746         int callid_created = ast_callid_threadstorage_auto(&callid);
2747
2748         switch (p->sig) {
2749         case SIG_PRI_LIB_HANDLE_CASES:
2750                 if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
2751                         /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
2752                         break;
2753                 }
2754                 /* Fall through */
2755         default:
2756                 /* Set to audio mode at this point */
2757                 audio = 1;
2758                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1) {
2759                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
2760                                 p->channel, audio, strerror(errno));
2761                 }
2762                 break;
2763         }
2764
2765         if (law != SIG_PRI_DEFLAW) {
2766                 dahdi_setlaw(p->subs[SUB_REAL].dfd, (law == SIG_PRI_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
2767         }
2768
2769         ast_copy_string(p->exten, exten, sizeof(p->exten));
2770
2771         switch (law) {
2772                 case SIG_PRI_DEFLAW:
2773                         newlaw = 0;
2774                         break;
2775                 case SIG_PRI_ALAW:
2776                         newlaw = DAHDI_LAW_ALAW;
2777                         break;
2778                 case SIG_PRI_ULAW:
2779                         newlaw = DAHDI_LAW_MULAW;
2780                         break;
2781         }
2782
2783         return dahdi_new_callid_clean(p, state, 0, SUB_REAL, newlaw, requestor ? ast_channel_linkedid(requestor) : "", callid, callid_created);
2784 }
2785 #endif  /* defined(HAVE_PRI) */
2786
2787 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law);
2788
2789 #if defined(HAVE_PRI) || defined(HAVE_SS7)
2790 /*!
2791  * \internal
2792  * \brief Open the PRI/SS7 channel media path.
2793  * \since 1.8
2794  *
2795  * \param p Channel private control structure.
2796  *
2797  * \return Nothing
2798  */
2799 static void my_pri_ss7_open_media(void *p)
2800 {
2801         struct dahdi_pvt *pvt = p;
2802         int res;
2803         int dfd;
2804         int set_val;
2805
2806         dfd = pvt->subs[SUB_REAL].dfd;
2807
2808         /* Open the media path. */
2809         set_val = 1;
2810         res = ioctl(dfd, DAHDI_AUDIOMODE, &set_val);
2811         if (res < 0) {
2812                 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n",
2813                         pvt->channel, strerror(errno));
2814         }
2815
2816         /* Set correct companding law for this call. */
2817         res = dahdi_setlaw(dfd, pvt->law);
2818         if (res < 0) {
2819                 ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pvt->channel);
2820         }
2821
2822         /* Set correct gain for this call. */
2823         if (pvt->digital) {
2824                 res = set_actual_gain(dfd, 0, 0, pvt->rxdrc, pvt->txdrc, pvt->law);
2825         } else {
2826                 res = set_actual_gain(dfd, pvt->rxgain, pvt->txgain, pvt->rxdrc, pvt->txdrc,
2827                         pvt->law);
2828         }
2829         if (res < 0) {
2830                 ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pvt->channel);
2831         }
2832
2833         if (pvt->dsp_features && pvt->dsp) {
2834                 ast_dsp_set_features(pvt->dsp, pvt->dsp_features);
2835                 pvt->dsp_features = 0;
2836         }
2837 }
2838 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
2839
2840 #if defined(HAVE_PRI)
2841 /*!
2842  * \internal
2843  * \brief Ask DAHDI to dial the given dial string.
2844  * \since 1.8.11
2845  *
2846  * \param p Channel private control structure.
2847  * \param dial_string String to pass to DAHDI to dial.
2848  *
2849  * \note The channel private lock needs to be held when calling.
2850  *
2851  * \return Nothing
2852  */
2853 static void my_pri_dial_digits(void *p, const char *dial_string)
2854 {
2855         char dial_str[DAHDI_MAX_DTMF_BUF];
2856         struct dahdi_pvt *pvt = p;
2857         int res;
2858
2859         snprintf(dial_str, sizeof(dial_str), "T%s", dial_string);
2860         res = dahdi_dial_str(pvt, DAHDI_DIAL_OP_APPEND, dial_str);
2861         if (!res) {
2862                 pvt->dialing = 1;
2863         }
2864 }
2865 #endif  /* defined(HAVE_PRI) */
2866
2867 static int unalloc_sub(struct dahdi_pvt *p, int x);
2868
2869 static int my_unallocate_sub(void *pvt, enum analog_sub analogsub)
2870 {
2871         struct dahdi_pvt *p = pvt;
2872
2873         return unalloc_sub(p, analogsub_to_dahdisub(analogsub));
2874 }
2875
2876 static int alloc_sub(struct dahdi_pvt *p, int x);
2877
2878 static int my_allocate_sub(void *pvt, enum analog_sub analogsub)
2879 {
2880         struct dahdi_pvt *p = pvt;
2881
2882         return alloc_sub(p, analogsub_to_dahdisub(analogsub));
2883 }
2884
2885 static int has_voicemail(struct dahdi_pvt *p);
2886
2887 static int my_has_voicemail(void *pvt)
2888 {
2889         struct dahdi_pvt *p = pvt;
2890
2891         return has_voicemail(p);
2892 }
2893
2894 static int my_play_tone(void *pvt, enum analog_sub sub, enum analog_tone tone)
2895 {
2896         struct dahdi_pvt *p = pvt;
2897         int index;
2898
2899         index = analogsub_to_dahdisub(sub);
2900
2901         return tone_zone_play_tone(p->subs[index].dfd, analog_tone_to_dahditone(tone));
2902 }
2903
2904 static enum analog_event dahdievent_to_analogevent(int event)
2905 {
2906         enum analog_event res;
2907
2908         switch (event) {
2909         case DAHDI_EVENT_ONHOOK:
2910                 res = ANALOG_EVENT_ONHOOK;
2911                 break;
2912         case DAHDI_EVENT_RINGOFFHOOK:
2913                 res = ANALOG_EVENT_RINGOFFHOOK;
2914                 break;
2915         case DAHDI_EVENT_WINKFLASH:
2916                 res = ANALOG_EVENT_WINKFLASH;
2917                 break;
2918         case DAHDI_EVENT_ALARM:
2919                 res = ANALOG_EVENT_ALARM;
2920                 break;
2921         case DAHDI_EVENT_NOALARM:
2922                 res = ANALOG_EVENT_NOALARM;
2923                 break;
2924         case DAHDI_EVENT_DIALCOMPLETE:
2925                 res = ANALOG_EVENT_DIALCOMPLETE;
2926                 break;
2927         case DAHDI_EVENT_RINGERON:
2928                 res = ANALOG_EVENT_RINGERON;
2929                 break;
2930         case DAHDI_EVENT_RINGEROFF:
2931                 res = ANALOG_EVENT_RINGEROFF;
2932                 break;
2933         case DAHDI_EVENT_HOOKCOMPLETE:
2934                 res = ANALOG_EVENT_HOOKCOMPLETE;
2935                 break;
2936         case DAHDI_EVENT_PULSE_START:
2937                 res = ANALOG_EVENT_PULSE_START;
2938                 break;
2939         case DAHDI_EVENT_POLARITY:
2940                 res = ANALOG_EVENT_POLARITY;
2941                 break;
2942         case DAHDI_EVENT_RINGBEGIN:
2943                 res = ANALOG_EVENT_RINGBEGIN;
2944                 break;
2945         case DAHDI_EVENT_EC_DISABLED:
2946                 res = ANALOG_EVENT_EC_DISABLED;
2947                 break;
2948         case DAHDI_EVENT_REMOVED:
2949                 res = ANALOG_EVENT_REMOVED;
2950                 break;
2951         case DAHDI_EVENT_NEONMWI_ACTIVE:
2952                 res = ANALOG_EVENT_NEONMWI_ACTIVE;
2953                 break;
2954         case DAHDI_EVENT_NEONMWI_INACTIVE:
2955                 res = ANALOG_EVENT_NEONMWI_INACTIVE;
2956                 break;
2957 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
2958         case DAHDI_EVENT_TX_CED_DETECTED:
2959                 res = ANALOG_EVENT_TX_CED_DETECTED;
2960                 break;
2961         case DAHDI_EVENT_RX_CED_DETECTED:
2962                 res = ANALOG_EVENT_RX_CED_DETECTED;
2963                 break;
2964         case DAHDI_EVENT_EC_NLP_DISABLED:
2965                 res = ANALOG_EVENT_EC_NLP_DISABLED;
2966                 break;
2967         case DAHDI_EVENT_EC_NLP_ENABLED:
2968                 res = ANALOG_EVENT_EC_NLP_ENABLED;
2969                 break;
2970 #endif
2971         case DAHDI_EVENT_PULSEDIGIT:
2972                 res = ANALOG_EVENT_PULSEDIGIT;
2973                 break;
2974         case DAHDI_EVENT_DTMFDOWN:
2975                 res = ANALOG_EVENT_DTMFDOWN;
2976                 break;
2977         case DAHDI_EVENT_DTMFUP:
2978                 res = ANALOG_EVENT_DTMFUP;
2979                 break;
2980         default:
2981                 switch(event & 0xFFFF0000) {
2982                 case DAHDI_EVENT_PULSEDIGIT:
2983                 case DAHDI_EVENT_DTMFDOWN:
2984                 case DAHDI_EVENT_DTMFUP:
2985                         /* The event includes a digit number in the low word.
2986                          * Converting it to a 'enum analog_event' would remove
2987                          * that information. Thus it is returned as-is.
2988                          */
2989                         return event;
2990                 }
2991
2992                 res = ANALOG_EVENT_ERROR;
2993                 break;
2994         }
2995
2996         return res;
2997 }
2998
2999 static inline int dahdi_wait_event(int fd);
3000
3001 static int my_wait_event(void *pvt)
3002 {
3003         struct dahdi_pvt *p = pvt;
3004
3005         return dahdi_wait_event(p->subs[SUB_REAL].dfd);
3006 }
3007
3008 static int my_get_event(void *pvt)
3009 {
3010         struct dahdi_pvt *p = pvt;
3011         int res;
3012
3013         if (p->fake_event) {
3014                 res = p->fake_event;
3015                 p->fake_event = 0;
3016         } else
3017                 res = dahdi_get_event(p->subs[SUB_REAL].dfd);
3018
3019         return dahdievent_to_analogevent(res);
3020 }
3021
3022 static int my_is_off_hook(void *pvt)
3023 {
3024         struct dahdi_pvt *p = pvt;
3025         int res;
3026         struct dahdi_params par;
3027
3028         memset(&par, 0, sizeof(par));
3029
3030         if (p->subs[SUB_REAL].dfd > -1)
3031                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
3032         else {
3033                 /* Assume not off hook on CVRS */
3034                 res = 0;
3035                 par.rxisoffhook = 0;
3036         }
3037         if (res) {
3038                 ast_log(LOG_WARNING, "Unable to check hook state on channel %d: %s\n", p->channel, strerror(errno));
3039         }
3040
3041         if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
3042                 /* When "onhook" that means no battery on the line, and thus
3043                 it is out of service..., if it's on a TDM card... If it's a channel
3044                 bank, there is no telling... */
3045                 return (par.rxbits > -1) || par.rxisoffhook;
3046         }
3047
3048         return par.rxisoffhook;
3049 }
3050
3051 static void dahdi_enable_ec(struct dahdi_pvt *p);
3052 static void dahdi_disable_ec(struct dahdi_pvt *p);
3053
3054 static int my_set_echocanceller(void *pvt, int enable)
3055 {
3056         struct dahdi_pvt *p = pvt;
3057
3058         if (enable)
3059                 dahdi_enable_ec(p);
3060         else
3061                 dahdi_disable_ec(p);
3062
3063         return 0;
3064 }
3065
3066 static int dahdi_ring_phone(struct dahdi_pvt *p);
3067
3068 static int my_ring(void *pvt)
3069 {
3070         struct dahdi_pvt *p = pvt;
3071
3072         return dahdi_ring_phone(p);
3073 }
3074
3075 static int my_flash(void *pvt)
3076 {
3077         struct dahdi_pvt *p = pvt;
3078         int func = DAHDI_FLASH;
3079         return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &func);
3080 }
3081
3082 static inline int dahdi_set_hook(int fd, int hs);
3083
3084 static int my_off_hook(void *pvt)
3085 {
3086         struct dahdi_pvt *p = pvt;
3087         return dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
3088 }
3089
3090 static void my_set_needringing(void *pvt, int value)
3091 {
3092         struct dahdi_pvt *p = pvt;
3093         p->subs[SUB_REAL].needringing = value;
3094 }
3095
3096 static void my_set_polarity(void *pvt, int value)
3097 {
3098         struct dahdi_pvt *p = pvt;
3099
3100         if (p->channel == CHAN_PSEUDO) {
3101                 return;
3102         }
3103         p->polarity = value;
3104         ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETPOLARITY, &value);
3105 }
3106
3107 static void my_start_polarityswitch(void *pvt)
3108 {
3109         struct dahdi_pvt *p = pvt;
3110
3111         if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
3112                 my_set_polarity(pvt, 0);
3113         }
3114 }
3115
3116 static void my_answer_polarityswitch(void *pvt)
3117 {
3118         struct dahdi_pvt *p = pvt;
3119
3120         if (!p->answeronpolarityswitch) {
3121                 return;
3122         }
3123
3124         my_set_polarity(pvt, 1);
3125 }
3126
3127 static void my_hangup_polarityswitch(void *pvt)
3128 {
3129         struct dahdi_pvt *p = pvt;
3130
3131         if (!p->hanguponpolarityswitch) {
3132                 return;
3133         }
3134
3135         if (p->answeronpolarityswitch) {
3136                 my_set_polarity(pvt, 0);
3137         } else {
3138                 my_set_polarity(pvt, 1);
3139         }
3140 }
3141
3142 static int my_start(void *pvt)
3143 {
3144         struct dahdi_pvt *p = pvt;
3145         int x = DAHDI_START;
3146
3147         return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
3148 }
3149
3150 static int my_dial_digits(void *pvt, enum analog_sub sub, struct analog_dialoperation *dop)
3151 {
3152         struct dahdi_pvt *p = pvt;
3153
3154         if (dop->op != ANALOG_DIAL_OP_REPLACE) {
3155                 ast_log(LOG_ERROR, "Fix the dial_digits callback!\n");
3156                 return -1;
3157         }
3158
3159         if (sub != ANALOG_SUB_REAL) {
3160                 ast_log(LOG_ERROR, "Trying to dial_digits '%s' on channel %d subchannel %d\n",
3161                         dop->dialstr, p->channel, sub);
3162                 return -1;
3163         }
3164
3165         return dahdi_dial_str(p, DAHDI_DIAL_OP_REPLACE, dop->dialstr);
3166 }
3167
3168 static void dahdi_train_ec(struct dahdi_pvt *p);
3169
3170 static int my_train_echocanceller(void *pvt)
3171 {
3172         struct dahdi_pvt *p = pvt;
3173
3174         dahdi_train_ec(p);
3175
3176         return 0;
3177 }
3178
3179 static int my_is_dialing(void *pvt, enum analog_sub sub)
3180 {
3181         struct dahdi_pvt *p = pvt;
3182         int index;
3183         int x;
3184
3185         index = analogsub_to_dahdisub(sub);
3186
3187         if (ioctl(p->subs[index].dfd, DAHDI_DIALING, &x)) {
3188                 ast_debug(1, "DAHDI_DIALING ioctl failed!\n");
3189                 return -1;
3190         }
3191
3192         return x;
3193 }
3194
3195 static int my_on_hook(void *pvt)
3196 {
3197         struct dahdi_pvt *p = pvt;
3198         return dahdi_set_hook(p->subs[ANALOG_SUB_REAL].dfd, DAHDI_ONHOOK);
3199 }
3200
3201 #if defined(HAVE_PRI)
3202 static void my_pri_fixup_chans(void *chan_old, void *chan_new)
3203 {
3204         struct dahdi_pvt *old_chan = chan_old;
3205         struct dahdi_pvt *new_chan = chan_new;
3206
3207         new_chan->owner = old_chan->owner;
3208         old_chan->owner = NULL;
3209         if (new_chan->owner) {
3210                 ast_channel_tech_pvt_set(new_chan->owner, new_chan);
3211                 ast_channel_internal_fd_set(new_chan->owner, 0, new_chan->subs[SUB_REAL].dfd);
3212                 new_chan->subs[SUB_REAL].owner = old_chan->subs[SUB_REAL].owner;
3213                 old_chan->subs[SUB_REAL].owner = NULL;
3214         }
3215         /* Copy any DSP that may be present */
3216         new_chan->dsp = old_chan->dsp;
3217         new_chan->dsp_features = old_chan->dsp_features;
3218         old_chan->dsp = NULL;
3219         old_chan->dsp_features = 0;
3220
3221         /* Transfer flags from the old channel. */
3222         new_chan->dialing = old_chan->dialing;
3223         new_chan->digital = old_chan->digital;
3224         new_chan->outgoing = old_chan->outgoing;
3225         old_chan->dialing = 0;
3226         old_chan->digital = 0;
3227         old_chan->outgoing = 0;
3228
3229         /* More stuff to transfer to the new channel. */
3230         new_chan->law = old_chan->law;
3231         strcpy(new_chan->dialstring, old_chan->dialstring);
3232 }
3233 #endif  /* defined(HAVE_PRI) */
3234
3235 #if defined(HAVE_PRI)
3236 static int sig_pri_tone_to_dahditone(enum sig_pri_tone tone)
3237 {
3238         switch (tone) {
3239         case SIG_PRI_TONE_RINGTONE:
3240                 return DAHDI_TONE_RINGTONE;
3241         case SIG_PRI_TONE_STUTTER:
3242                 return DAHDI_TONE_STUTTER;
3243         case SIG_PRI_TONE_CONGESTION:
3244                 return DAHDI_TONE_CONGESTION;
3245         case SIG_PRI_TONE_DIALTONE:
3246                 return DAHDI_TONE_DIALTONE;
3247         case SIG_PRI_TONE_DIALRECALL:
3248                 return DAHDI_TONE_DIALRECALL;
3249         case SIG_PRI_TONE_INFO:
3250                 return DAHDI_TONE_INFO;
3251         case SIG_PRI_TONE_BUSY:
3252                 return DAHDI_TONE_BUSY;
3253         default:
3254                 return -1;
3255         }
3256 }
3257 #endif  /* defined(HAVE_PRI) */
3258
3259 #if defined(HAVE_PRI)
3260 static void my_handle_dchan_exception(struct sig_pri_span *pri, int index)
3261 {
3262         int x;
3263
3264         ioctl(pri->fds[index], DAHDI_GETEVENT, &x);
3265         switch (x) {
3266         case DAHDI_EVENT_NONE:
3267                 break;
3268         case DAHDI_EVENT_ALARM:
3269         case DAHDI_EVENT_NOALARM:
3270                 if (sig_pri_is_alarm_ignored(pri)) {
3271                         break;
3272                 }
3273                 /* Fall through */
3274         default:
3275                 ast_log(LOG_NOTICE, "PRI got event: %s (%d) on D-channel of span %d\n",
3276                         event2str(x), x, pri->span);
3277                 break;
3278         }
3279         /* Keep track of alarm state */
3280         switch (x) {
3281         case DAHDI_EVENT_ALARM:
3282                 pri_event_alarm(pri, index, 0);
3283                 break;
3284         case DAHDI_EVENT_NOALARM:
3285                 pri_event_noalarm(pri, index, 0);
3286                 break;
3287         default:
3288                 break;
3289         }
3290 }
3291 #endif  /* defined(HAVE_PRI) */
3292
3293 #if defined(HAVE_PRI)
3294 static int my_pri_play_tone(void *pvt, enum sig_pri_tone tone)
3295 {
3296         struct dahdi_pvt *p = pvt;
3297
3298         return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_pri_tone_to_dahditone(tone));
3299 }
3300 #endif  /* defined(HAVE_PRI) */
3301
3302 #if defined(HAVE_PRI) || defined(HAVE_SS7)
3303 /*!
3304  * \internal
3305  * \brief Set the caller id information.
3306  * \since 1.8
3307  *
3308  * \param pvt DAHDI private structure
3309  * \param caller Caller-id information to set.
3310  *
3311  * \return Nothing
3312  */
3313 static void my_set_callerid(void *pvt, const struct ast_party_caller *caller)
3314 {
3315         struct dahdi_pvt *p = pvt;
3316
3317         ast_copy_string(p->cid_num,
3318                 S_COR(caller->id.number.valid, caller->id.number.str, ""),
3319                 sizeof(p->cid_num));
3320         ast_copy_string(p->cid_name,
3321                 S_COR(caller->id.name.valid, caller->id.name.str, ""),
3322                 sizeof(p->cid_name));
3323         ast_copy_string(p->cid_subaddr,
3324                 S_COR(caller->id.subaddress.valid, caller->id.subaddress.str, ""),
3325                 sizeof(p->cid_subaddr));
3326         p->cid_ton = caller->id.number.plan;
3327         p->callingpres = ast_party_id_presentation(&caller->id);
3328         if (caller->id.tag) {
3329                 ast_copy_string(p->cid_tag, caller->id.tag, sizeof(p->cid_tag));
3330         }
3331         ast_copy_string(p->cid_ani,
3332                 S_COR(caller->ani.number.valid, caller->ani.number.str, ""),
3333                 sizeof(p->cid_ani));
3334         p->cid_ani2 = caller->ani2;
3335 }
3336 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
3337
3338 #if defined(HAVE_PRI) || defined(HAVE_SS7)
3339 /*!
3340  * \internal
3341  * \brief Set the Dialed Number Identifier.
3342  * \since 1.8
3343  *
3344  * \param pvt DAHDI private structure
3345  * \param dnid Dialed Number Identifier string.
3346  *
3347  * \return Nothing
3348  */
3349 static void my_set_dnid(void *pvt, const char *dnid)
3350 {
3351         struct dahdi_pvt *p = pvt;
3352
3353         ast_copy_string(p->dnid, dnid, sizeof(p->dnid));
3354 }
3355 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
3356
3357 #if defined(HAVE_PRI)
3358 /*!
3359  * \internal
3360  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
3361  * \since 1.8
3362  *
3363  * \param pvt DAHDI private structure
3364  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
3365  *
3366  * \return Nothing
3367  */
3368 static void my_set_rdnis(void *pvt, const char *rdnis)
3369 {
3370         struct dahdi_pvt *p = pvt;
3371
3372         ast_copy_string(p->rdnis, rdnis, sizeof(p->rdnis));
3373 }
3374 #endif  /* defined(HAVE_PRI) */
3375
3376 #if defined(HAVE_PRI)
3377 /*!
3378  * \internal
3379  * \brief Make a dialstring for native ISDN CC to recall properly.
3380  * \since 1.8
3381  *
3382  * \param priv Channel private control structure.
3383  * \param buf Where to put the modified dialstring.
3384  * \param buf_size Size of modified dialstring buffer.
3385  *
3386  * \details
3387  * original dialstring:
3388  * DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
3389  *
3390  * The modified dialstring will have prefixed the channel-group section
3391  * with the ISDN channel restriction.
3392  *
3393  * buf:
3394  * DAHDI/i<span>-(g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
3395  *
3396  * The routine will check to see if the ISDN channel restriction is already
3397  * in the original dialstring.
3398  *
3399  * \return Nothing
3400  */
3401 static void my_pri_make_cc_dialstring(void *priv, char *buf, size_t buf_size)
3402 {
3403         char *dial;
3404         struct dahdi_pvt *pvt;
3405         AST_DECLARE_APP_ARGS(args,
3406                 AST_APP_ARG(tech);      /* channel technology token */
3407                 AST_APP_ARG(group);     /* channel/group token */
3408                 //AST_APP_ARG(ext);     /* extension token */
3409                 //AST_APP_ARG(opts);    /* options token */
3410                 //AST_APP_ARG(other);   /* Any remining unused arguments */
3411         );
3412
3413         pvt = priv;
3414         dial = ast_strdupa(pvt->dialstring);
3415         AST_NONSTANDARD_APP_ARGS(args, dial, '/');
3416         if (!args.tech) {
3417                 ast_copy_string(buf, pvt->dialstring, buf_size);
3418                 return;
3419         }
3420         if (!args.group) {
3421                 /* Append the ISDN span channel restriction to the dialstring. */
3422                 snprintf(buf, buf_size, "%s/i%d-", args.tech, pvt->pri->span);
3423                 return;
3424         }
3425         if (isdigit(args.group[0]) || args.group[0] == 'i' || strchr(args.group, '!')) {
3426                 /* The ISDN span channel restriction is not needed or already
3427                  * in the dialstring. */
3428                 ast_copy_string(buf, pvt->dialstring, buf_size);
3429                 return;
3430         }
3431         /* Insert the ISDN span channel restriction into the dialstring. */
3432         snprintf(buf, buf_size, "%s/i%d-%s", args.tech, pvt->pri->span, args.group);
3433 }
3434 #endif  /* defined(HAVE_PRI) */
3435
3436 #if defined(HAVE_PRI)
3437 /*!
3438  * \internal
3439  * \brief Reevaluate the PRI span device state.
3440  * \since 1.8
3441  *
3442  * \param pri Asterisk D channel control structure.
3443  *
3444  * \return Nothing
3445  *
3446  * \note Assumes the pri->lock is already obtained.
3447  */
3448 static void dahdi_pri_update_span_devstate(struct sig_pri_span *pri)
3449 {
3450         unsigned idx;
3451         unsigned num_b_chans;   /* Number of B channels provisioned on the span. */
3452         unsigned in_use;                /* Number of B channels in use on the span. */
3453         unsigned in_alarm;              /* TRUE if the span is in alarm condition. */
3454         enum ast_device_state new_state;
3455
3456         /* Count the number of B channels and the number of B channels in use. */
3457         num_b_chans = 0;
3458         in_use = 0;
3459         in_alarm = 1;
3460         for (idx = pri->numchans; idx--;) {
3461                 if (pri->pvts[idx] && !pri->pvts[idx]->no_b_channel) {
3462                         /* This is a B channel interface. */
3463                         ++num_b_chans;
3464                         if (!sig_pri_is_chan_available(pri->pvts[idx])) {
3465                                 ++in_use;
3466                         }
3467                         if (!pri->pvts[idx]->inalarm) {
3468                                 /* There is a channel that is not in alarm. */
3469                                 in_alarm = 0;
3470                         }
3471                 }
3472         }
3473
3474         /* Update the span congestion device state and report any change. */
3475         if (in_alarm) {
3476                 new_state = AST_DEVICE_UNAVAILABLE;
3477         } else {
3478                 new_state = num_b_chans == in_use ? AST_DEVICE_BUSY : AST_DEVICE_NOT_INUSE;
3479         }
3480         if (pri->congestion_devstate != new_state) {
3481                 pri->congestion_devstate = new_state;
3482                 ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/congestion", pri->span);
3483         }
3484 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
3485         /* Update the span threshold device state and report any change. */
3486         if (in_alarm) {
3487                 new_state = AST_DEVICE_UNAVAILABLE;
3488         } else if (!in_use) {
3489                 new_state = AST_DEVICE_NOT_INUSE;
3490         } else if (!pri->user_busy_threshold) {
3491                 new_state = in_use < num_b_chans ? AST_DEVICE_INUSE : AST_DEVICE_BUSY;
3492         } else {
3493                 new_state = in_use < pri->user_busy_threshold ? AST_DEVICE_INUSE
3494                         : AST_DEVICE_BUSY;
3495         }
3496         if (pri->threshold_devstate != new_state) {
3497                 pri->threshold_devstate = new_state;
3498                 ast_devstate_changed(AST_DEVICE_UNKNOWN, "DAHDI/I%d/threshold", pri->span);
3499         }
3500 #endif  /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
3501 }
3502 #endif  /* defined(HAVE_PRI) */
3503
3504 #if defined(HAVE_PRI)
3505 /*!
3506  * \internal
3507  * \brief Reference this module.
3508  * \since 1.8
3509  *
3510  * \return Nothing
3511  */
3512 static void my_module_ref(void)
3513 {
3514         ast_module_ref(ast_module_info->self);
3515 }
3516 #endif  /* defined(HAVE_PRI) */
3517
3518 #if defined(HAVE_PRI)
3519 /*!
3520  * \internal
3521  * \brief Unreference this module.
3522  * \since 1.8
3523  *
3524  * \return Nothing
3525  */
3526 static void my_module_unref(void)
3527 {
3528         ast_module_unref(ast_module_info->self);
3529 }
3530 #endif  /* defined(HAVE_PRI) */
3531
3532 #if defined(HAVE_PRI)
3533 #if defined(HAVE_PRI_CALL_WAITING)
3534 static void my_pri_init_config(void *priv, struct sig_pri_span *pri);
3535 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
3536 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri);
3537
3538 struct sig_pri_callback sig_pri_callbacks =
3539 {
3540         .handle_dchan_exception = my_handle_dchan_exception,
3541         .play_tone = my_pri_play_tone,
3542         .set_echocanceller = my_set_echocanceller,
3543         .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
3544         .lock_private = my_lock_private,
3545         .unlock_private = my_unlock_private,
3546         .deadlock_avoidance_private = my_deadlock_avoidance_private,
3547         .new_ast_channel = my_new_pri_ast_channel,
3548         .fixup_chans = my_pri_fixup_chans,
3549         .set_alarm = my_set_alarm,
3550         .set_dialing = my_set_dialing,
3551         .set_outgoing = my_set_outgoing,
3552         .set_digital = my_set_digital,
3553         .set_callerid = my_set_callerid,
3554         .set_dnid = my_set_dnid,
3555         .set_rdnis = my_set_rdnis,
3556         .new_nobch_intf = dahdi_new_pri_nobch_channel,
3557 #if defined(HAVE_PRI_CALL_WAITING)
3558         .init_config = my_pri_init_config,
3559 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
3560         .get_orig_dialstring = my_get_orig_dialstring,
3561         .make_cc_dialstring = my_pri_make_cc_dialstring,
3562         .update_span_devstate = dahdi_pri_update_span_devstate,
3563         .module_ref = my_module_ref,
3564         .module_unref = my_module_unref,
3565         .dial_digits = my_pri_dial_digits,
3566         .open_media = my_pri_ss7_open_media,
3567         .ami_channel_event = my_ami_channel_event,
3568 };
3569 #endif  /* defined(HAVE_PRI) */
3570
3571 #if defined(HAVE_SS7)
3572 /*!
3573  * \internal
3574  * \brief Handle the SS7 link exception.
3575  * \since 1.8
3576  *
3577  * \param linkset Controlling linkset for the channel.
3578  * \param which Link index of the signaling channel.
3579  *
3580  * \return Nothing
3581  */
3582 static void my_handle_link_exception(struct sig_ss7_linkset *linkset, int which)
3583 {
3584         int event;
3585
3586         if (ioctl(linkset->fds[which], DAHDI_GETEVENT, &event)) {
3587                 ast_log(LOG_ERROR, "SS7: Error in exception retrieval on span %d/%d!\n",
3588                         linkset->span, which);
3589                 return;
3590         }
3591         switch (event) {
3592         case DAHDI_EVENT_NONE:
3593                 break;
3594         case DAHDI_EVENT_ALARM:
3595                 ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
3596                         event2str(event), event, linkset->span, which);
3597                 sig_ss7_link_alarm(linkset, which);
3598                 break;
3599         case DAHDI_EVENT_NOALARM:
3600                 ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
3601                         event2str(event), event, linkset->span, which);
3602                 sig_ss7_link_noalarm(linkset, which);
3603                 break;
3604         default:
3605                 ast_log(LOG_NOTICE, "SS7 got event: %s(%d) on span %d/%d\n",
3606                         event2str(event), event, linkset->span, which);
3607                 break;
3608         }
3609 }
3610 #endif  /* defined(HAVE_SS7) */
3611
3612 #if defined(HAVE_SS7)
3613 static void my_ss7_set_loopback(void *pvt, int enable)
3614 {
3615         struct dahdi_pvt *p = pvt;
3616
3617         if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_LOOPBACK, &enable)) {
3618                 ast_log(LOG_WARNING, "Unable to set loopback on channel %d: %s\n", p->channel,
3619                         strerror(errno));
3620         }
3621 }
3622 #endif  /* defined(HAVE_SS7) */
3623
3624 #if defined(HAVE_SS7)
3625 /*!
3626  * \internal
3627  * \brief Create a new asterisk channel structure for SS7.
3628  * \since 1.8
3629  *
3630  * \param pvt Private channel structure.
3631  * \param state Initial state of new channel.
3632  * \param law Combanding law to use.
3633  * \param exten Dialplan extension for incoming call.
3634  * \param requestor Channel requesting this new channel.
3635  *
3636  * \retval ast_channel on success.
3637  * \retval NULL on error.
3638  */
3639 static struct ast_channel *my_new_ss7_ast_channel(void *pvt, int state, enum sig_ss7_law law, char *exten, const struct ast_channel *requestor)
3640 {
3641         struct dahdi_pvt *p = pvt;
3642         int audio;
3643         int newlaw;
3644         struct ast_callid *callid = NULL;
3645         int callid_created = ast_callid_threadstorage_auto(&callid);
3646
3647         /* Set to audio mode at this point */
3648         audio = 1;
3649         if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1)
3650                 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
3651                         p->channel, audio, strerror(errno));
3652
3653         if (law != SIG_SS7_DEFLAW) {
3654                 dahdi_setlaw(p->subs[SUB_REAL].dfd,
3655                         (law == SIG_SS7_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
3656         }
3657
3658         ast_copy_string(p->exten, exten, sizeof(p->exten));
3659
3660         newlaw = -1;
3661         switch (law) {
3662         case SIG_SS7_DEFLAW:
3663                 newlaw = 0;
3664                 break;
3665         case SIG_SS7_ALAW:
3666                 newlaw = DAHDI_LAW_ALAW;
3667                 break;
3668         case SIG_SS7_ULAW:
3669                 newlaw = DAHDI_LAW_MULAW;
3670                 break;
3671         }
3672         return dahdi_new_callid_clean(p, state, 0, SUB_REAL, newlaw, requestor ? ast_channel_linkedid(requestor) : "", callid, callid_created);
3673 }
3674 #endif  /* defined(HAVE_SS7) */
3675
3676 #if defined(HAVE_SS7)
3677 static int sig_ss7_tone_to_dahditone(enum sig_ss7_tone tone)
3678 {
3679         switch (tone) {
3680         case SIG_SS7_TONE_RINGTONE:
3681                 return DAHDI_TONE_RINGTONE;
3682         case SIG_SS7_TONE_STUTTER:
3683                 return DAHDI_TONE_STUTTER;
3684         case SIG_SS7_TONE_CONGESTION:
3685                 return DAHDI_TONE_CONGESTION;
3686         case SIG_SS7_TONE_DIALTONE:
3687                 return DAHDI_TONE_DIALTONE;
3688         case SIG_SS7_TONE_DIALRECALL:
3689                 return DAHDI_TONE_DIALRECALL;
3690         case SIG_SS7_TONE_INFO:
3691                 return DAHDI_TONE_INFO;
3692         case SIG_SS7_TONE_BUSY:
3693                 return DAHDI_TONE_BUSY;
3694         default:
3695                 return -1;
3696         }
3697 }
3698 #endif  /* defined(HAVE_SS7) */
3699
3700 #if defined(HAVE_SS7)
3701 static int my_ss7_play_tone(void *pvt, enum sig_ss7_tone tone)
3702 {
3703         struct dahdi_pvt *p = pvt;
3704
3705         return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_ss7_tone_to_dahditone(tone));
3706 }
3707 #endif  /* defined(HAVE_SS7) */
3708
3709 #if defined(HAVE_SS7)
3710 struct sig_ss7_callback sig_ss7_callbacks =
3711 {
3712         .lock_private = my_lock_private,
3713         .unlock_private = my_unlock_private,
3714         .deadlock_avoidance_private = my_deadlock_avoidance_private,
3715
3716         .set_echocanceller = my_set_echocanceller,
3717         .set_loopback = my_ss7_set_loopback,
3718
3719         .new_ast_channel = my_new_ss7_ast_channel,
3720         .play_tone = my_ss7_play_tone,
3721
3722         .handle_link_exception = my_handle_link_exception,
3723         .set_alarm = my_set_alarm,
3724         .set_dialing = my_set_dialing,
3725         .set_outgoing = my_set_outgoing,
3726         .set_digital = my_set_digital,
3727         .set_inservice = my_set_inservice,
3728         .set_locallyblocked = my_set_locallyblocked,
3729         .set_remotelyblocked = my_set_remotelyblocked,
3730         .set_callerid = my_set_callerid,
3731         .set_dnid = my_set_dnid,
3732         .open_media = my_pri_ss7_open_media,
3733 };
3734 #endif  /* defined(HAVE_SS7) */
3735
3736 /*!
3737  * \brief Send MWI state change
3738  *
3739  * \arg mailbox_full This is the mailbox associated with the FXO line that the
3740  *      MWI state has changed on.
3741