res_smdi: convert to astobj2
[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 /*! \li \ref chan_dahdi.c uses the configuration file \ref chan_dahdi.conf
38  * \addtogroup configuration_file
39  */
40
41 /*! \page chan_dahdi.conf chan_dahdi.conf
42  * \verbinclude chan_dahdi.conf.sample
43  */
44
45 /*** MODULEINFO
46         <use type="module">res_smdi</use>
47         <depend>dahdi</depend>
48         <depend>tonezone</depend>
49         <use type="external">pri</use>
50         <use type="external">ss7</use>
51         <use type="external">openr2</use>
52         <support_level>core</support_level>
53  ***/
54
55 #include "asterisk.h"
56
57 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
58
59 #if defined(__NetBSD__) || defined(__FreeBSD__)
60 #include <pthread.h>
61 #include <signal.h>
62 #else
63 #include <sys/signal.h>
64 #endif
65 #include <sys/stat.h>
66 #include <math.h>
67
68 #include "sig_analog.h"
69 /* Analog signaling is currently still present in chan_dahdi for use with
70  * radio. Sig_analog does not currently handle any radio operations. If
71  * radio only uses analog signaling, then the radio handling logic could
72  * be placed in sig_analog and the duplicated code could be removed.
73  */
74
75 #if defined(HAVE_PRI)
76 #include "sig_pri.h"
77 #ifndef PRI_RESTART
78 #error "Upgrade your libpri"
79 #endif
80 #endif  /* defined(HAVE_PRI) */
81
82 #if defined(HAVE_SS7)
83 #include "sig_ss7.h"
84 #if !defined(LIBSS7_ABI_COMPATIBILITY)
85 #error "Upgrade your libss7"
86 #elif LIBSS7_ABI_COMPATIBILITY != 2
87 #error "Your installed libss7 is not compatible"
88 #endif
89 #endif  /* defined(HAVE_SS7) */
90
91 #if defined(HAVE_OPENR2)
92 /* put this here until sig_mfcr2 comes along */
93 #define SIG_MFCR2_MAX_CHANNELS  672             /*!< No more than a DS3 per trunk group */
94 #endif  /* defined(HAVE_OPENR2) */
95
96 #include "asterisk/lock.h"
97 #include "asterisk/channel.h"
98 #include "asterisk/config.h"
99 #include "asterisk/module.h"
100 #include "asterisk/pbx.h"
101 #include "asterisk/file.h"
102 #include "asterisk/ulaw.h"
103 #include "asterisk/alaw.h"
104 #include "asterisk/callerid.h"
105 #include "asterisk/adsi.h"
106 #include "asterisk/cli.h"
107 #include "asterisk/pickup.h"
108 #include "asterisk/features.h"
109 #include "asterisk/musiconhold.h"
110 #include "asterisk/say.h"
111 #include "asterisk/tdd.h"
112 #include "asterisk/app.h"
113 #include "asterisk/dsp.h"
114 #include "asterisk/astdb.h"
115 #include "asterisk/manager.h"
116 #include "asterisk/causes.h"
117 #include "asterisk/term.h"
118 #include "asterisk/utils.h"
119 #include "asterisk/transcap.h"
120 #include "asterisk/stringfields.h"
121 #include "asterisk/abstract_jb.h"
122 #include "asterisk/smdi.h"
123 #include "asterisk/devicestate.h"
124 #include "asterisk/paths.h"
125 #include "asterisk/ccss.h"
126 #include "asterisk/data.h"
127 #include "asterisk/features_config.h"
128 #include "asterisk/bridge.h"
129 #include "asterisk/stasis_channels.h"
130 #include "asterisk/parking.h"
131 #include "asterisk/format_cache.h"
132 #include "chan_dahdi.h"
133 #include "dahdi/bridge_native_dahdi.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         <manager name="PRIDebugSet" language="en_US">
300                 <synopsis>
301                         Set PRI debug levels for a span
302                 </synopsis>
303                 <syntax>
304                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
305                         <parameter name="Span" required="true">
306                                 <para>Which span to affect.</para>
307                         </parameter>
308                         <parameter name="Level" required="true">
309                                 <para>What debug level to set. May be a numerical value or a text value from the list below</para>
310                                 <enumlist>
311                                         <enum name="off" />
312                                         <enum name="on" />
313                                         <enum name="hex" />
314                                         <enum name="intense" />
315                                 </enumlist>
316                         </parameter>
317                 </syntax>
318                 <description>
319                         <para>Equivalent to the CLI command "pri set debug &lt;level&gt; span &lt;span&gt;".</para>
320                 </description>
321         </manager>
322         <manager name="PRIDebugFileSet" language="en_US">
323                 <synopsis>
324                         Set the file used for PRI debug message output
325                 </synopsis>
326                 <syntax>
327                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
328                         <parameter name="File" required="true">
329                                 <para>Path of file to write debug output.</para>
330                         </parameter>
331                 </syntax>
332                 <description>
333                         <para>Equivalent to the CLI command "pri set debug file &lt;output-file&gt;"</para>
334                 </description>
335         </manager>
336         <manager name="PRIDebugFileUnset" language="en_US">
337                 <synopsis>
338                         Disables file output for PRI debug messages
339                 </synopsis>
340                 <syntax>
341                         <xi:include xpointer="xpointer(/docs/manager[@name='Login']/syntax/parameter[@name='ActionID'])" />
342                 </syntax>
343         </manager>
344         <managerEvent language="en_US" name="AlarmClear">
345                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
346                         <synopsis>Raised when an alarm is cleared on a DAHDI channel.</synopsis>
347                         <syntax>
348                                 <parameter name="DAHDIChannel">
349                                         <para>The DAHDI channel on which the alarm was cleared.</para>
350                                         <note><para>This is not an Asterisk channel identifier.</para></note>
351                                 </parameter>
352                         </syntax>
353                 </managerEventInstance>
354         </managerEvent>
355         <managerEvent language="en_US" name="SpanAlarmClear">
356                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
357                         <synopsis>Raised when an alarm is cleared on a DAHDI span.</synopsis>
358                         <syntax>
359                                 <parameter name="Span">
360                                         <para>The span on which the alarm was cleared.</para>
361                                 </parameter>
362                         </syntax>
363                 </managerEventInstance>
364         </managerEvent>
365         <managerEvent language="en_US" name="DNDState">
366                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
367                         <synopsis>Raised when the Do Not Disturb state is changed on a DAHDI channel.</synopsis>
368                         <syntax>
369                                 <parameter name="DAHDIChannel">
370                                         <para>The DAHDI channel on which DND status changed.</para>
371                                         <note><para>This is not an Asterisk channel identifier.</para></note>
372                                 </parameter>
373                                 <parameter name="Status">
374                                         <enumlist>
375                                                 <enum name="enabled"/>
376                                                 <enum name="disabled"/>
377                                         </enumlist>
378                                 </parameter>
379                         </syntax>
380                 </managerEventInstance>
381         </managerEvent>
382         <managerEvent language="en_US" name="Alarm">
383                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
384                         <synopsis>Raised when an alarm is set on a DAHDI channel.</synopsis>
385                         <syntax>
386                                 <parameter name="DAHDIChannel">
387                                         <para>The channel on which the alarm occurred.</para>
388                                         <note><para>This is not an Asterisk channel identifier.</para></note>
389                                 </parameter>
390                                 <parameter name="Alarm">
391                                         <para>A textual description of the alarm that occurred.</para>
392                                 </parameter>
393                         </syntax>
394                 </managerEventInstance>
395         </managerEvent>
396         <managerEvent language="en_US" name="SpanAlarm">
397                 <managerEventInstance class="EVENT_FLAG_SYSTEM">
398                         <synopsis>Raised when an alarm is set on a DAHDI span.</synopsis>
399                         <syntax>
400                                 <parameter name="Span">
401                                         <para>The span on which the alarm occurred.</para>
402                                 </parameter>
403                                 <parameter name="Alarm">
404                                         <para>A textual description of the alarm that occurred.</para>
405                                 </parameter>
406                         </syntax>
407                 </managerEventInstance>
408         </managerEvent>
409         <managerEvent language="en_US" name="DAHDIChannel">
410                 <managerEventInstance class="EVENT_FLAG_CALL">
411                         <synopsis>Raised when a DAHDI channel is created or an underlying technology is associated with a DAHDI channel.</synopsis>
412                         <syntax>
413                                 <channel_snapshot/>
414                                 <parameter name="DAHDISpan">
415                                         <para>The DAHDI span associated with this channel.</para>
416                                 </parameter>
417                                 <parameter name="DAHDIChannel">
418                                         <para>The DAHDI channel associated with this channel.</para>
419                                 </parameter>
420                         </syntax>
421                 </managerEventInstance>
422         </managerEvent>
423  ***/
424
425 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
426
427 static const char * const lbostr[] = {
428 "0 db (CSU)/0-133 feet (DSX-1)",
429 "133-266 feet (DSX-1)",
430 "266-399 feet (DSX-1)",
431 "399-533 feet (DSX-1)",
432 "533-655 feet (DSX-1)",
433 "-7.5db (CSU)",
434 "-15db (CSU)",
435 "-22.5db (CSU)"
436 };
437
438 /*! Global jitterbuffer configuration - by default, jb is disabled
439  *  \note Values shown here match the defaults shown in chan_dahdi.conf.sample */
440 static struct ast_jb_conf default_jbconf =
441 {
442         .flags = 0,
443         .max_size = 200,
444         .resync_threshold = 1000,
445         .impl = "fixed",
446         .target_extra = 40,
447 };
448 static struct ast_jb_conf global_jbconf;
449
450 /*!
451  * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
452  * the user hangs up to reset the state machine so ring works properly.
453  * This is used to be able to support kewlstart by putting the zhone in
454  * groundstart mode since their forward disconnect supervision is entirely
455  * broken even though their documentation says it isn't and their support
456  * is entirely unwilling to provide any assistance with their channel banks
457  * even though their web site says they support their products for life.
458  */
459 /* #define ZHONE_HACK */
460
461 /*! \brief Typically, how many rings before we should send Caller*ID */
462 #define DEFAULT_CIDRINGS 1
463
464 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? ast_format_alaw : ast_format_ulaw)
465
466
467 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
468 #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))
469
470 static const char tdesc[] = "DAHDI Telephony"
471 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
472         " w/"
473         #if defined(HAVE_PRI)
474                 "PRI"
475         #endif  /* defined(HAVE_PRI) */
476         #if defined(HAVE_SS7)
477                 #if defined(HAVE_PRI)
478                 " & "
479                 #endif  /* defined(HAVE_PRI) */
480                 "SS7"
481         #endif  /* defined(HAVE_SS7) */
482         #if defined(HAVE_OPENR2)
483                 #if defined(HAVE_PRI) || defined(HAVE_SS7)
484                 " & "
485                 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
486                 "MFC/R2"
487         #endif  /* defined(HAVE_OPENR2) */
488 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2) */
489 ;
490
491 static const char config[] = "chan_dahdi.conf";
492
493 #ifdef LOTS_OF_SPANS
494 #define NUM_SPANS       DAHDI_MAX_SPANS
495 #else
496 #define NUM_SPANS               32
497 #endif
498
499 #define CHAN_PSEUDO     -2
500
501 #define CALLPROGRESS_PROGRESS           1
502 #define CALLPROGRESS_FAX_OUTGOING       2
503 #define CALLPROGRESS_FAX_INCOMING       4
504 #define CALLPROGRESS_FAX                (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
505
506 #define NUM_CADENCE_MAX 25
507 static int num_cadence = 4;
508 static int user_has_defined_cadences = 0;
509
510 static int has_pseudo;
511
512 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
513         { { 125, 125, 2000, 4000 } },                   /*!< Quick chirp followed by normal ring */
514         { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
515         { { 125, 125, 125, 125, 125, 4000 } },  /*!< Three short bursts */
516         { { 1000, 500, 2500, 5000 } },  /*!< Long ring */
517 };
518
519 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
520  * is 1, the second pause is 2 and so on.
521  */
522
523 static int cidrings[NUM_CADENCE_MAX] = {
524         2,                                                                              /*!< Right after first long ring */
525         4,                                                                              /*!< Right after long part */
526         3,                                                                              /*!< After third chirp */
527         2,                                                                              /*!< Second spell */
528 };
529
530 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
531 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
532
533 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
534                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
535
536 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
537 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
538
539 static char defaultcic[64] = "";
540 static char defaultozz[64] = "";
541
542 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
543 static char mwimonitornotify[PATH_MAX] = "";
544 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
545 static int  mwisend_rpas = 0;
546 #endif
547
548 static char progzone[10] = "";
549
550 static int usedistinctiveringdetection = 0;
551 static int distinctiveringaftercid = 0;
552
553 static int numbufs = 4;
554
555 static int mwilevel = 512;
556 static int dtmfcid_level = 256;
557
558 #define REPORT_CHANNEL_ALARMS 1
559 #define REPORT_SPAN_ALARMS    2
560 static int report_alarms = REPORT_CHANNEL_ALARMS;
561
562 #ifdef HAVE_PRI
563 static int pridebugfd = -1;
564 static char pridebugfilename[1024] = "";
565 #endif
566
567 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
568 static int firstdigittimeout = 16000;
569
570 /*! \brief How long to wait for following digits (FXO logic) */
571 static int gendigittimeout = 8000;
572
573 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
574 static int matchdigittimeout = 3000;
575
576 /*! \brief Protect the interface list (of dahdi_pvt's) */
577 AST_MUTEX_DEFINE_STATIC(iflock);
578
579
580 static int ifcount = 0;
581
582 #ifdef HAVE_PRI
583 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
584 #endif
585
586 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
587    when it's doing something critical. */
588 AST_MUTEX_DEFINE_STATIC(monlock);
589
590 /*! \brief This is the thread for the monitor which checks for input on the channels
591    which are not currently in use. */
592 static pthread_t monitor_thread = AST_PTHREADT_NULL;
593 static ast_cond_t ss_thread_complete;
594 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
595 AST_MUTEX_DEFINE_STATIC(restart_lock);
596 static int ss_thread_count = 0;
597 static int num_restart_pending = 0;
598
599 static int restart_monitor(void);
600
601 static int dahdi_sendtext(struct ast_channel *c, const char *text);
602
603 static void mwi_event_cb(void *userdata, struct stasis_subscription *sub, struct stasis_message *msg)
604 {
605         /* This module does not handle MWI in an event-based manner.  However, it
606          * subscribes to MWI for each mailbox that is configured so that the core
607          * knows that we care about it.  Then, chan_dahdi will get the MWI from the
608          * event cache instead of checking the mailbox directly. */
609 }
610
611 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
612 static inline int dahdi_get_event(int fd)
613 {
614         int j;
615         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
616                 return -1;
617         return j;
618 }
619
620 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
621 static inline int dahdi_wait_event(int fd)
622 {
623         int i, j = 0;
624         i = DAHDI_IOMUX_SIGEVENT;
625         if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
626                 return -1;
627         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
628                 return -1;
629         return j;
630 }
631
632 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
633 #define READ_SIZE 160
634
635 #define MASK_AVAIL              (1 << 0)        /*!< Channel available for PRI use */
636 #define MASK_INUSE              (1 << 1)        /*!< Channel currently in use */
637
638 #define CALLWAITING_SILENT_SAMPLES              ((300 * 8) / READ_SIZE) /*!< 300 ms */
639 #define CALLWAITING_REPEAT_SAMPLES              ((10000 * 8) / READ_SIZE) /*!< 10,000 ms */
640 #define CALLWAITING_SUPPRESS_SAMPLES    ((100 * 8) / READ_SIZE) /*!< 100 ms */
641 #define CIDCW_EXPIRE_SAMPLES                    ((500 * 8) / READ_SIZE) /*!< 500 ms */
642 #define MIN_MS_SINCE_FLASH                              ((2000) )       /*!< 2000 ms */
643 #define DEFAULT_RINGT                                   ((8000 * 8) / READ_SIZE) /*!< 8,000 ms */
644 #define DEFAULT_DIALTONE_DETECT_TIMEOUT ((10000 * 8) / READ_SIZE) /*!< 10,000 ms */
645
646 /*!
647  * \brief Configured ring timeout base.
648  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
649  */
650 static int ringt_base = DEFAULT_RINGT;
651
652 #if defined(HAVE_SS7)
653
654 struct dahdi_ss7 {
655         struct sig_ss7_linkset ss7;
656 };
657
658 static struct dahdi_ss7 linksets[NUM_SPANS];
659
660 static int cur_ss7type = -1;
661 static int cur_slc = -1;
662 static int cur_linkset = -1;
663 static int cur_pointcode = -1;
664 static int cur_cicbeginswith = -1;
665 static int cur_adjpointcode = -1;
666 static int cur_networkindicator = -1;
667 static int cur_defaultdpc = -1;
668 #endif  /* defined(HAVE_SS7) */
669
670 #ifdef HAVE_OPENR2
671 struct dahdi_mfcr2_conf {
672         openr2_variant_t variant;
673         int mfback_timeout;
674         int metering_pulse_timeout;
675         int max_ani;
676         int max_dnis;
677 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 2
678         int dtmf_time_on;
679         int dtmf_time_off;
680 #endif
681 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 3
682         int dtmf_end_timeout;
683 #endif
684         signed int get_ani_first:2;
685 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
686         signed int skip_category_request:2;
687 #endif
688         unsigned int call_files:1;
689         unsigned int allow_collect_calls:1;
690         unsigned int charge_calls:1;
691         unsigned int accept_on_offer:1;
692         unsigned int forced_release:1;
693         unsigned int double_answer:1;
694         signed int immediate_accept:2;
695 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 2
696         signed int dtmf_dialing:2;
697         signed int dtmf_detection:2;
698 #endif
699         char logdir[OR2_MAX_PATH];
700         char r2proto_file[OR2_MAX_PATH];
701         openr2_log_level_t loglevel;
702         openr2_calling_party_category_t category;
703 };
704
705 /* MFC-R2 pseudo-link structure */
706 struct dahdi_mfcr2 {
707         pthread_t r2master;                    /*!< Thread of master */
708         openr2_context_t *protocol_context;    /*!< OpenR2 context handle */
709         struct dahdi_pvt *pvts[SIG_MFCR2_MAX_CHANNELS];     /*!< Member channel pvt structs */
710         int numchans;                          /*!< Number of channels in this R2 block */
711         struct dahdi_mfcr2_conf conf;         /*!< Configuration used to setup this pseudo-link */
712 };
713
714 /* malloc'd array of malloc'd r2links */
715 static struct dahdi_mfcr2 **r2links;
716 /* how many r2links have been malloc'd */
717 static int r2links_count = 0;
718
719 #endif /* HAVE_OPENR2 */
720
721 #ifdef HAVE_PRI
722
723 struct dahdi_pri {
724         int dchannels[SIG_PRI_NUM_DCHANS];              /*!< What channel are the dchannels on */
725         int mastertrunkgroup;                                   /*!< What trunk group is our master */
726         int prilogicalspan;                                             /*!< Logical span number within trunk group */
727         struct sig_pri_span pri;
728 };
729
730 static struct dahdi_pri pris[NUM_SPANS];
731
732 #if defined(HAVE_PRI_CCSS)
733 /*! DAHDI PRI CCSS agent and monitor type name. */
734 static const char dahdi_pri_cc_type[] = "DAHDI/PRI";
735 #endif  /* defined(HAVE_PRI_CCSS) */
736
737 #else
738 /*! Shut up the compiler */
739 struct dahdi_pri;
740 #endif
741
742 /* Polarity states */
743 #define POLARITY_IDLE   0
744 #define POLARITY_REV    1
745
746 const char * const subnames[] = {
747         "Real",
748         "Callwait",
749         "Threeway"
750 };
751
752 #define DATA_EXPORT_DAHDI_PVT(MEMBER)                                   \
753         MEMBER(dahdi_pvt, cid_rxgain, AST_DATA_DOUBLE)                  \
754         MEMBER(dahdi_pvt, rxgain, AST_DATA_DOUBLE)                      \
755         MEMBER(dahdi_pvt, txgain, AST_DATA_DOUBLE)                      \
756         MEMBER(dahdi_pvt, txdrc, AST_DATA_DOUBLE)                       \
757         MEMBER(dahdi_pvt, rxdrc, AST_DATA_DOUBLE)                       \
758         MEMBER(dahdi_pvt, adsi, AST_DATA_BOOLEAN)                       \
759         MEMBER(dahdi_pvt, answeronpolarityswitch, AST_DATA_BOOLEAN)     \
760         MEMBER(dahdi_pvt, busydetect, AST_DATA_BOOLEAN)                 \
761         MEMBER(dahdi_pvt, callreturn, AST_DATA_BOOLEAN)                 \
762         MEMBER(dahdi_pvt, callwaiting, AST_DATA_BOOLEAN)                \
763         MEMBER(dahdi_pvt, callwaitingcallerid, AST_DATA_BOOLEAN)        \
764         MEMBER(dahdi_pvt, cancallforward, AST_DATA_BOOLEAN)             \
765         MEMBER(dahdi_pvt, canpark, AST_DATA_BOOLEAN)                    \
766         MEMBER(dahdi_pvt, confirmanswer, AST_DATA_BOOLEAN)              \
767         MEMBER(dahdi_pvt, destroy, AST_DATA_BOOLEAN)                    \
768         MEMBER(dahdi_pvt, didtdd, AST_DATA_BOOLEAN)                     \
769         MEMBER(dahdi_pvt, dialednone, AST_DATA_BOOLEAN)                 \
770         MEMBER(dahdi_pvt, dialing, AST_DATA_BOOLEAN)                    \
771         MEMBER(dahdi_pvt, digital, AST_DATA_BOOLEAN)                    \
772         MEMBER(dahdi_pvt, dnd, AST_DATA_BOOLEAN)                        \
773         MEMBER(dahdi_pvt, echobreak, AST_DATA_BOOLEAN)                  \
774         MEMBER(dahdi_pvt, echocanbridged, AST_DATA_BOOLEAN)             \
775         MEMBER(dahdi_pvt, echocanon, AST_DATA_BOOLEAN)                  \
776         MEMBER(dahdi_pvt, faxhandled, AST_DATA_BOOLEAN)                 \
777         MEMBER(dahdi_pvt, usefaxbuffers, AST_DATA_BOOLEAN)              \
778         MEMBER(dahdi_pvt, bufferoverrideinuse, AST_DATA_BOOLEAN)        \
779         MEMBER(dahdi_pvt, firstradio, AST_DATA_BOOLEAN)                 \
780         MEMBER(dahdi_pvt, hanguponpolarityswitch, AST_DATA_BOOLEAN)     \
781         MEMBER(dahdi_pvt, hardwaredtmf, AST_DATA_BOOLEAN)               \
782         MEMBER(dahdi_pvt, hidecallerid, AST_DATA_BOOLEAN)               \
783         MEMBER(dahdi_pvt, hidecalleridname, AST_DATA_BOOLEAN)           \
784         MEMBER(dahdi_pvt, ignoredtmf, AST_DATA_BOOLEAN)                 \
785         MEMBER(dahdi_pvt, immediate, AST_DATA_BOOLEAN)                  \
786         MEMBER(dahdi_pvt, inalarm, AST_DATA_BOOLEAN)                    \
787         MEMBER(dahdi_pvt, mate, AST_DATA_BOOLEAN)                       \
788         MEMBER(dahdi_pvt, outgoing, AST_DATA_BOOLEAN)                   \
789         MEMBER(dahdi_pvt, permcallwaiting, AST_DATA_BOOLEAN)            \
790         MEMBER(dahdi_pvt, priindication_oob, AST_DATA_BOOLEAN)          \
791         MEMBER(dahdi_pvt, priexclusive, AST_DATA_BOOLEAN)               \
792         MEMBER(dahdi_pvt, pulse, AST_DATA_BOOLEAN)                      \
793         MEMBER(dahdi_pvt, pulsedial, AST_DATA_BOOLEAN)                  \
794         MEMBER(dahdi_pvt, restartpending, AST_DATA_BOOLEAN)             \
795         MEMBER(dahdi_pvt, restrictcid, AST_DATA_BOOLEAN)                \
796         MEMBER(dahdi_pvt, threewaycalling, AST_DATA_BOOLEAN)            \
797         MEMBER(dahdi_pvt, transfer, AST_DATA_BOOLEAN)                   \
798         MEMBER(dahdi_pvt, use_callerid, AST_DATA_BOOLEAN)               \
799         MEMBER(dahdi_pvt, use_callingpres, AST_DATA_BOOLEAN)            \
800         MEMBER(dahdi_pvt, usedistinctiveringdetection, AST_DATA_BOOLEAN)        \
801         MEMBER(dahdi_pvt, dahditrcallerid, AST_DATA_BOOLEAN)                    \
802         MEMBER(dahdi_pvt, transfertobusy, AST_DATA_BOOLEAN)                     \
803         MEMBER(dahdi_pvt, mwimonitor_neon, AST_DATA_BOOLEAN)                    \
804         MEMBER(dahdi_pvt, mwimonitor_fsk, AST_DATA_BOOLEAN)                     \
805         MEMBER(dahdi_pvt, mwimonitor_rpas, AST_DATA_BOOLEAN)                    \
806         MEMBER(dahdi_pvt, mwimonitoractive, AST_DATA_BOOLEAN)                   \
807         MEMBER(dahdi_pvt, mwisendactive, AST_DATA_BOOLEAN)                      \
808         MEMBER(dahdi_pvt, inservice, AST_DATA_BOOLEAN)                          \
809         MEMBER(dahdi_pvt, locallyblocked, AST_DATA_UNSIGNED_INTEGER)            \
810         MEMBER(dahdi_pvt, remotelyblocked, AST_DATA_UNSIGNED_INTEGER)           \
811         MEMBER(dahdi_pvt, manages_span_alarms, AST_DATA_BOOLEAN)                \
812         MEMBER(dahdi_pvt, use_smdi, AST_DATA_BOOLEAN)                           \
813         MEMBER(dahdi_pvt, context, AST_DATA_STRING)                             \
814         MEMBER(dahdi_pvt, defcontext, AST_DATA_STRING)                          \
815         MEMBER(dahdi_pvt, description, AST_DATA_STRING)                         \
816         MEMBER(dahdi_pvt, exten, AST_DATA_STRING)                               \
817         MEMBER(dahdi_pvt, language, AST_DATA_STRING)                            \
818         MEMBER(dahdi_pvt, mohinterpret, AST_DATA_STRING)                        \
819         MEMBER(dahdi_pvt, mohsuggest, AST_DATA_STRING)                          \
820         MEMBER(dahdi_pvt, parkinglot, AST_DATA_STRING)
821
822 AST_DATA_STRUCTURE(dahdi_pvt, DATA_EXPORT_DAHDI_PVT);
823
824 static struct dahdi_pvt *iflist = NULL; /*!< Main interface list start */
825 static struct dahdi_pvt *ifend = NULL;  /*!< Main interface list end */
826
827 #if defined(HAVE_PRI)
828 struct doomed_pri {
829         struct sig_pri_span *pri;
830         AST_LIST_ENTRY(doomed_pri) list;
831 };
832 static AST_LIST_HEAD_STATIC(doomed_pris, doomed_pri);
833
834 static void pri_destroy_span(struct sig_pri_span *pri);
835
836 static struct dahdi_parms_pseudo {
837         int buf_no;                                     /*!< Number of buffers */
838         int buf_policy;                         /*!< Buffer policy */
839         int faxbuf_no;              /*!< Number of Fax buffers */
840         int faxbuf_policy;          /*!< Fax buffer policy */
841 } dahdi_pseudo_parms;
842 #endif  /* defined(HAVE_PRI) */
843
844 /*! \brief Channel configuration from chan_dahdi.conf .
845  * This struct is used for parsing the [channels] section of chan_dahdi.conf.
846  * Generally there is a field here for every possible configuration item.
847  *
848  * The state of fields is saved along the parsing and whenever a 'channel'
849  * statement is reached, the current dahdi_chan_conf is used to configure the
850  * channel (struct dahdi_pvt)
851  *
852  * \see dahdi_chan_init for the default values.
853  */
854 struct dahdi_chan_conf {
855         struct dahdi_pvt chan;
856 #ifdef HAVE_PRI
857         struct dahdi_pri pri;
858 #endif
859
860 #if defined(HAVE_SS7)
861         struct dahdi_ss7 ss7;
862 #endif  /* defined(HAVE_SS7) */
863
864 #ifdef HAVE_OPENR2
865         struct dahdi_mfcr2_conf mfcr2;
866 #endif
867         struct dahdi_params timing;
868         int is_sig_auto; /*!< Use channel signalling from DAHDI? */
869         /*! Continue configuration even if a channel is not there. */
870         int ignore_failed_channels;
871
872         /*!
873          * \brief The serial port to listen for SMDI data on
874          * \note Set from the "smdiport" string read in from chan_dahdi.conf
875          */
876         char smdi_port[SMDI_MAX_FILENAME_LEN];
877
878         /*!
879          * \brief Don't create channels below this number
880          * \note by default is 0 (no limit)
881          */
882         int wanted_channels_start;
883
884         /*!
885          * \brief Don't create channels above this number (infinity by default)
886          * \note by default is 0 (special value that means "no limit").
887          */
888         int wanted_channels_end;
889 };
890
891 /*! returns a new dahdi_chan_conf with default values (by-value) */
892 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
893 {
894         /* recall that if a field is not included here it is initialized
895          * to 0 or equivalent
896          */
897         struct dahdi_chan_conf conf = {
898 #ifdef HAVE_PRI
899                 .pri.pri = {
900                         .nsf = PRI_NSF_NONE,
901                         .switchtype = PRI_SWITCH_NI2,
902                         .dialplan = PRI_UNKNOWN + 1,
903                         .localdialplan = PRI_NATIONAL_ISDN + 1,
904                         .nodetype = PRI_CPE,
905                         .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
906
907 #if defined(HAVE_PRI_CCSS)
908                         .cc_ptmp_recall_mode = 1,/* specificRecall */
909                         .cc_qsig_signaling_link_req = 1,/* retain */
910                         .cc_qsig_signaling_link_rsp = 1,/* retain */
911 #endif  /* defined(HAVE_PRI_CCSS) */
912
913                         .minunused = 2,
914                         .idleext = "",
915                         .idledial = "",
916                         .internationalprefix = "",
917                         .nationalprefix = "",
918                         .localprefix = "",
919                         .privateprefix = "",
920                         .unknownprefix = "",
921                         .colp_send = SIG_PRI_COLP_UPDATE,
922                         .resetinterval = -1,
923                 },
924 #endif
925 #if defined(HAVE_SS7)
926                 .ss7.ss7 = {
927                         .called_nai = SS7_NAI_NATIONAL,
928                         .calling_nai = SS7_NAI_NATIONAL,
929                         .internationalprefix = "",
930                         .nationalprefix = "",
931                         .subscriberprefix = "",
932                         .unknownprefix = "",
933                         .networkroutedprefix = ""
934                 },
935 #endif  /* defined(HAVE_SS7) */
936 #ifdef HAVE_OPENR2
937                 .mfcr2 = {
938                         .variant = OR2_VAR_ITU,
939                         .mfback_timeout = -1,
940                         .metering_pulse_timeout = -1,
941                         .max_ani = 10,
942                         .max_dnis = 4,
943                         .get_ani_first = -1,
944 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
945                         .skip_category_request = -1,
946 #endif
947                         .call_files = 0,
948                         .allow_collect_calls = 0,
949                         .charge_calls = 1,
950                         .accept_on_offer = 1,
951                         .forced_release = 0,
952                         .double_answer = 0,
953                         .immediate_accept = -1,
954 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 2
955                         .dtmf_dialing = -1,
956                         .dtmf_detection = -1,
957                         .dtmf_time_on = OR2_DEFAULT_DTMF_ON,
958                         .dtmf_time_off = OR2_DEFAULT_DTMF_OFF,
959 #endif
960 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 3
961                         .dtmf_end_timeout = -1,
962 #endif
963                         .logdir = "",
964                         .r2proto_file = "",
965                         .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
966                         .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
967                 },
968 #endif
969                 .chan = {
970                         .context = "default",
971                         .cid_num = "",
972                         .cid_name = "",
973                         .cid_tag = "",
974                         .mohinterpret = "default",
975                         .mohsuggest = "",
976                         .parkinglot = "",
977                         .transfertobusy = 1,
978
979                         .cid_signalling = CID_SIG_BELL,
980                         .cid_start = CID_START_RING,
981                         .dahditrcallerid = 0,
982                         .use_callerid = 1,
983                         .sig = -1,
984                         .outsigmod = -1,
985
986                         .cid_rxgain = +5.0,
987
988                         .tonezone = -1,
989
990                         .echocancel.head.tap_length = 1,
991
992                         .busycount = 3,
993
994                         .accountcode = "",
995
996                         .mailbox = "",
997
998 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
999                         .mwisend_fsk = 1,
1000 #endif
1001                         .polarityonanswerdelay = 600,
1002
1003                         .sendcalleridafter = DEFAULT_CIDRINGS,
1004
1005                         .buf_policy = DAHDI_POLICY_IMMEDIATE,
1006                         .buf_no = numbufs,
1007                         .usefaxbuffers = 0,
1008                         .cc_params = ast_cc_config_params_init(),
1009                 },
1010                 .timing = {
1011                         .prewinktime = -1,
1012                         .preflashtime = -1,
1013                         .winktime = -1,
1014                         .flashtime = -1,
1015                         .starttime = -1,
1016                         .rxwinktime = -1,
1017                         .rxflashtime = -1,
1018                         .debouncetime = -1
1019                 },
1020                 .is_sig_auto = 1,
1021                 .ignore_failed_channels = 1,
1022                 .smdi_port = "/dev/ttyS0",
1023         };
1024
1025         return conf;
1026 }
1027
1028
1029 static struct ast_channel *dahdi_request(const char *type, struct ast_format_cap *cap,
1030         const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor,
1031         const char *data, int *cause);
1032 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
1033 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
1034 static int dahdi_sendtext(struct ast_channel *c, const char *text);
1035 static int dahdi_call(struct ast_channel *ast, const char *rdest, int timeout);
1036 static int dahdi_hangup(struct ast_channel *ast);
1037 static int dahdi_answer(struct ast_channel *ast);
1038 static struct ast_frame *dahdi_read(struct ast_channel *ast);
1039 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
1040 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
1041 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
1042 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1043 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1044 static int dahdi_queryoption(struct ast_channel *chan, int option, void *data, int *datalen);
1045 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
1046 static int dahdi_func_write(struct ast_channel *chan, const char *function, char *data, const char *value);
1047 static int dahdi_devicestate(const char *data);
1048 static int dahdi_cc_callback(struct ast_channel *inbound, const char *dest, ast_cc_callback_fn callback);
1049
1050 static struct ast_channel_tech dahdi_tech = {
1051         .type = "DAHDI",
1052         .description = tdesc,
1053         .requester = dahdi_request,
1054         .send_digit_begin = dahdi_digit_begin,
1055         .send_digit_end = dahdi_digit_end,
1056         .send_text = dahdi_sendtext,
1057         .call = dahdi_call,
1058         .hangup = dahdi_hangup,
1059         .answer = dahdi_answer,
1060         .read = dahdi_read,
1061         .write = dahdi_write,
1062         .exception = dahdi_exception,
1063         .indicate = dahdi_indicate,
1064         .fixup = dahdi_fixup,
1065         .setoption = dahdi_setoption,
1066         .queryoption = dahdi_queryoption,
1067         .func_channel_read = dahdi_func_read,
1068         .func_channel_write = dahdi_func_write,
1069         .devicestate = dahdi_devicestate,
1070         .cc_callback = dahdi_cc_callback,
1071 };
1072
1073 #define GET_CHANNEL(p) ((p)->channel)
1074
1075 static enum analog_sigtype dahdisig_to_analogsig(int sig)
1076 {
1077         switch (sig) {
1078         case SIG_FXOLS:
1079                 return ANALOG_SIG_FXOLS;
1080         case SIG_FXOGS:
1081                 return ANALOG_SIG_FXOGS;
1082         case SIG_FXOKS:
1083                 return ANALOG_SIG_FXOKS;
1084         case SIG_FXSLS:
1085                 return ANALOG_SIG_FXSLS;
1086         case SIG_FXSGS:
1087                 return ANALOG_SIG_FXSGS;
1088         case SIG_FXSKS:
1089                 return ANALOG_SIG_FXSKS;
1090         case SIG_EMWINK:
1091                 return ANALOG_SIG_EMWINK;
1092         case SIG_EM:
1093                 return ANALOG_SIG_EM;
1094         case SIG_EM_E1:
1095                 return ANALOG_SIG_EM_E1;
1096         case SIG_FEATD:
1097                 return ANALOG_SIG_FEATD;
1098         case SIG_FEATDMF:
1099                 return ANALOG_SIG_FEATDMF;
1100         case SIG_E911:
1101                 return SIG_E911;
1102         case SIG_FGC_CAMA:
1103                 return ANALOG_SIG_FGC_CAMA;
1104         case SIG_FGC_CAMAMF:
1105                 return ANALOG_SIG_FGC_CAMAMF;
1106         case SIG_FEATB:
1107                 return ANALOG_SIG_FEATB;
1108         case SIG_SFWINK:
1109                 return ANALOG_SIG_SFWINK;
1110         case SIG_SF:
1111                 return ANALOG_SIG_SF;
1112         case SIG_SF_FEATD:
1113                 return ANALOG_SIG_SF_FEATD;
1114         case SIG_SF_FEATDMF:
1115                 return ANALOG_SIG_SF_FEATDMF;
1116         case SIG_FEATDMF_TA:
1117                 return ANALOG_SIG_FEATDMF_TA;
1118         case SIG_SF_FEATB:
1119                 return ANALOG_SIG_FEATB;
1120         default:
1121                 return -1;
1122         }
1123 }
1124
1125
1126 static int analog_tone_to_dahditone(enum analog_tone tone)
1127 {
1128         switch (tone) {
1129         case ANALOG_TONE_RINGTONE:
1130                 return DAHDI_TONE_RINGTONE;
1131         case ANALOG_TONE_STUTTER:
1132                 return DAHDI_TONE_STUTTER;
1133         case ANALOG_TONE_CONGESTION:
1134                 return DAHDI_TONE_CONGESTION;
1135         case ANALOG_TONE_DIALTONE:
1136                 return DAHDI_TONE_DIALTONE;
1137         case ANALOG_TONE_DIALRECALL:
1138                 return DAHDI_TONE_DIALRECALL;
1139         case ANALOG_TONE_INFO:
1140                 return DAHDI_TONE_INFO;
1141         default:
1142                 return -1;
1143         }
1144 }
1145
1146 static int analogsub_to_dahdisub(enum analog_sub analogsub)
1147 {
1148         int index;
1149
1150         switch (analogsub) {
1151         case ANALOG_SUB_REAL:
1152                 index = SUB_REAL;
1153                 break;
1154         case ANALOG_SUB_CALLWAIT:
1155                 index = SUB_CALLWAIT;
1156                 break;
1157         case ANALOG_SUB_THREEWAY:
1158                 index = SUB_THREEWAY;
1159                 break;
1160         default:
1161                 ast_log(LOG_ERROR, "Unidentified sub!\n");
1162                 index = SUB_REAL;
1163         }
1164
1165         return index;
1166 }
1167
1168 /*!
1169  * \internal
1170  * \brief release all members on the doomed pris list
1171  * \since 13.0
1172  *
1173  * Called priodically by the monitor threads to release spans marked for
1174  * removal.
1175  */
1176 static void release_doomed_pris(void)
1177 {
1178 #ifdef HAVE_PRI
1179         struct doomed_pri *entry;
1180
1181         AST_LIST_LOCK(&doomed_pris);
1182         while ((entry = AST_LIST_REMOVE_HEAD(&doomed_pris, list))) {
1183                 /* The span destruction must be done with this lock not held */
1184                 AST_LIST_UNLOCK(&doomed_pris);
1185                 ast_debug(4, "Destroying span %d from doomed queue.\n",
1186                                 entry->pri->span);
1187                 pri_destroy_span(entry->pri);
1188                 ast_free(entry);
1189                 AST_LIST_LOCK(&doomed_pris);
1190         }
1191         AST_LIST_UNLOCK(&doomed_pris);
1192 #endif
1193 }
1194
1195 #ifdef HAVE_PRI
1196 /*!
1197  * \brief Queue a span for destruction
1198  * \since 13.0
1199  *
1200  * \param pri the span to destroy
1201  *
1202  * Add a span to the list of spans to be destroyed later on
1203  * by the monitor thread. Allows destroying a span while holding its
1204  * lock.
1205  */
1206 static void pri_queue_for_destruction(struct sig_pri_span *pri)
1207 {
1208         struct doomed_pri *entry;
1209
1210         AST_LIST_LOCK(&doomed_pris);
1211         AST_LIST_TRAVERSE(&doomed_pris, entry, list) {
1212                 if (entry->pri == pri) {
1213                         AST_LIST_UNLOCK(&doomed_pris);
1214                         return;
1215                 }
1216         }
1217         entry = ast_calloc(sizeof(struct doomed_pri), 1);
1218         if (!entry) {
1219                 /* Nothing useful to do here. Panic? */
1220                 ast_log(LOG_WARNING, "Failed allocating memory for a doomed_pri.\n");
1221                 AST_LIST_UNLOCK(&doomed_pris);
1222                 return;
1223         }
1224         entry->pri = pri;
1225         ast_debug(4, "Queue span %d for destruction.\n", pri->span);
1226         AST_LIST_INSERT_TAIL(&doomed_pris, entry, list);
1227         AST_LIST_UNLOCK(&doomed_pris);
1228 }
1229 #endif
1230
1231 /*!
1232  * \internal
1233  * \brief Send a dial string to DAHDI.
1234  * \since 12.0.0
1235  *
1236  * \param pvt DAHDI private pointer
1237  * \param operation DAHDI dial operation to do to string
1238  * \param dial_str Dial string to send
1239  *
1240  * \retval 0 on success.
1241  * \retval non-zero on error.
1242  */
1243 static int dahdi_dial_str(struct dahdi_pvt *pvt, int operation, const char *dial_str)
1244 {
1245         int res;
1246         int offset;
1247         const char *pos;
1248         struct dahdi_dialoperation zo = {
1249                 .op = operation,
1250         };
1251
1252         /* Convert the W's to ww. */
1253         pos = dial_str;
1254         for (offset = 0; offset < sizeof(zo.dialstr) - 1; ++offset) {
1255                 if (!*pos) {
1256                         break;
1257                 }
1258                 if (*pos == 'W') {
1259                         /* Convert 'W' to "ww" */
1260                         ++pos;
1261                         if (offset >= sizeof(zo.dialstr) - 3) {
1262                                 /* No room to expand */
1263                                 break;
1264                         }
1265                         zo.dialstr[offset] = 'w';
1266                         ++offset;
1267                         zo.dialstr[offset] = 'w';
1268                         continue;
1269                 }
1270                 zo.dialstr[offset] = *pos++;
1271         }
1272         /* The zo initialization has already terminated the dialstr. */
1273
1274         ast_debug(1, "Channel %d: Dial str '%s' expanded to '%s' sent to DAHDI_DIAL.\n",
1275                 pvt->channel, dial_str, zo.dialstr);
1276         res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo);
1277         if (res) {
1278                 ast_log(LOG_WARNING, "Channel %d: Couldn't dial '%s': %s\n",
1279                         pvt->channel, dial_str, strerror(errno));
1280         }
1281
1282         return res;
1283 }
1284
1285 static enum analog_event dahdievent_to_analogevent(int event);
1286 static int bump_gains(struct dahdi_pvt *p);
1287 static int dahdi_setlinear(int dfd, int linear);
1288
1289 static int my_start_cid_detect(void *pvt, int cid_signalling)
1290 {
1291         struct dahdi_pvt *p = pvt;
1292         int index = SUB_REAL;
1293         p->cs = callerid_new(cid_signalling);
1294         if (!p->cs) {
1295                 ast_log(LOG_ERROR, "Unable to alloc callerid\n");
1296                 return -1;
1297         }
1298         bump_gains(p);
1299         dahdi_setlinear(p->subs[index].dfd, 0);
1300
1301         return 0;
1302 }
1303
1304 static int my_stop_cid_detect(void *pvt)
1305 {
1306         struct dahdi_pvt *p = pvt;
1307         int index = SUB_REAL;
1308         if (p->cs)
1309                 callerid_free(p->cs);
1310         dahdi_setlinear(p->subs[index].dfd, p->subs[index].linear);
1311         return 0;
1312 }
1313
1314 static int my_get_callerid(void *pvt, char *namebuf, char *numbuf, enum analog_event *ev, size_t timeout)
1315 {
1316         struct dahdi_pvt *p = pvt;
1317         struct analog_pvt *analog_p = p->sig_pvt;
1318         struct pollfd poller;
1319         char *name, *num;
1320         int index = SUB_REAL;
1321         int res;
1322         unsigned char buf[256];
1323         int flags;
1324
1325         poller.fd = p->subs[SUB_REAL].dfd;
1326         poller.events = POLLPRI | POLLIN;
1327         poller.revents = 0;
1328
1329         res = poll(&poller, 1, timeout);
1330
1331         if (poller.revents & POLLPRI) {
1332                 *ev = dahdievent_to_analogevent(dahdi_get_event(p->subs[SUB_REAL].dfd));
1333                 return 1;
1334         }
1335
1336         if (poller.revents & POLLIN) {
1337                 /*** NOTES ***/
1338                 /* Change API: remove cid_signalling from get_callerid, add a new start_cid_detect and stop_cid_detect function
1339                  * to enable slin mode and allocate cid detector. get_callerid should be able to be called any number of times until
1340                  * either a timeout occurs or CID is detected (returns 0). returning 1 should be event received, and -1 should be
1341                  * a failure and die, and returning 2 means no event was received. */
1342                 res = read(p->subs[index].dfd, buf, sizeof(buf));
1343                 if (res < 0) {
1344                         ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
1345                         return -1;
1346                 }
1347
1348                 if (analog_p->ringt > 0) {
1349                         if (!(--analog_p->ringt)) {
1350                                 /* only return if we timeout from a ring event */
1351                                 return -1;
1352                         }
1353                 }
1354
1355                 if (p->cid_signalling == CID_SIG_V23_JP) {
1356                         res = callerid_feed_jp(p->cs, buf, res, AST_LAW(p));
1357                 } else {
1358                         res = callerid_feed(p->cs, buf, res, AST_LAW(p));
1359                 }
1360                 if (res < 0) {
1361                         /*
1362                          * The previous diagnostic message output likely
1363                          * explains why it failed.
1364                          */
1365                         ast_log(LOG_WARNING, "Failed to decode CallerID\n");
1366                         return -1;
1367                 }
1368
1369                 if (res == 1) {
1370                         callerid_get(p->cs, &name, &num, &flags);
1371                         if (name)
1372                                 ast_copy_string(namebuf, name, ANALOG_MAX_CID);
1373                         if (num)
1374                                 ast_copy_string(numbuf, num, ANALOG_MAX_CID);
1375
1376                         ast_debug(1, "CallerID number: %s, name: %s, flags=%d\n", num, name, flags);
1377                         return 0;
1378                 }
1379         }
1380
1381         *ev = ANALOG_EVENT_NONE;
1382         return 2;
1383 }
1384
1385 static const char *event2str(int event);
1386 static int restore_gains(struct dahdi_pvt *p);
1387
1388 static int my_distinctive_ring(struct ast_channel *chan, void *pvt, int idx, int *ringdata)
1389 {
1390         unsigned char buf[256];
1391         int distMatches;
1392         int curRingData[RING_PATTERNS];
1393         int receivedRingT;
1394         int counter1;
1395         int counter;
1396         int i;
1397         int res;
1398         int checkaftercid = 0;
1399
1400         struct dahdi_pvt *p = pvt;
1401         struct analog_pvt *analog_p = p->sig_pvt;
1402
1403         if (ringdata == NULL) {
1404                 ringdata = curRingData;
1405         } else {
1406                 checkaftercid = 1;
1407         }
1408
1409         /* We must have a ring by now, so, if configured, lets try to listen for
1410          * distinctive ringing */
1411         if ((checkaftercid && distinctiveringaftercid) || !checkaftercid) {
1412                 /* Clear the current ring data array so we don't have old data in it. */
1413                 for (receivedRingT = 0; receivedRingT < RING_PATTERNS; receivedRingT++)
1414                         ringdata[receivedRingT] = 0;
1415                 receivedRingT = 0;
1416                 if (checkaftercid && distinctiveringaftercid)
1417                         ast_verb(3, "Detecting post-CID distinctive ring\n");
1418                 /* Check to see if context is what it should be, if not set to be. */
1419                 else if (strcmp(p->context,p->defcontext) != 0) {
1420                         ast_copy_string(p->context, p->defcontext, sizeof(p->context));
1421                         ast_channel_context_set(chan, p->defcontext);
1422                 }
1423
1424                 for (;;) {
1425                         i = DAHDI_IOMUX_READ | DAHDI_IOMUX_SIGEVENT;
1426                         if ((res = ioctl(p->subs[idx].dfd, DAHDI_IOMUX, &i))) {
1427                                 ast_log(LOG_WARNING, "I/O MUX failed: %s\n", strerror(errno));
1428                                 ast_hangup(chan);
1429                                 return 1;
1430                         }
1431                         if (i & DAHDI_IOMUX_SIGEVENT) {
1432                                 res = dahdi_get_event(p->subs[idx].dfd);
1433                                 if (res == DAHDI_EVENT_NOALARM) {
1434                                         p->inalarm = 0;
1435                                         analog_p->inalarm = 0;
1436                                 }
1437                                 ast_log(LOG_NOTICE, "Got event %d (%s)...\n", res, event2str(res));
1438                                 res = 0;
1439                                 /* Let us detect distinctive ring */
1440
1441                                 ringdata[receivedRingT] = analog_p->ringt;
1442
1443                                 if (analog_p->ringt < analog_p->ringt_base/2)
1444                                         break;
1445                                 /* Increment the ringT counter so we can match it against
1446                                    values in chan_dahdi.conf for distinctive ring */
1447                                 if (++receivedRingT == RING_PATTERNS)
1448                                         break;
1449                         } else if (i & DAHDI_IOMUX_READ) {
1450                                 res = read(p->subs[idx].dfd, buf, sizeof(buf));
1451                                 if (res < 0) {
1452                                         if (errno != ELAST) {
1453                                                 ast_log(LOG_WARNING, "read returned error: %s\n", strerror(errno));
1454                                                 ast_hangup(chan);
1455                                                 return 1;
1456                                         }
1457                                         break;
1458                                 }
1459                                 if (analog_p->ringt > 0) {
1460                                         if (!(--analog_p->ringt)) {
1461                                                 res = -1;
1462                                                 break;
1463                                         }
1464                                 }
1465                         }
1466                 }
1467         }
1468         if ((checkaftercid && usedistinctiveringdetection) || !checkaftercid) {
1469                 /* this only shows up if you have n of the dring patterns filled in */
1470                 ast_verb(3, "Detected ring pattern: %d,%d,%d\n",ringdata[0],ringdata[1],ringdata[2]);
1471                 for (counter = 0; counter < 3; counter++) {
1472                 /* Check to see if the rings we received match any of the ones in chan_dahdi.conf for this channel */
1473                         distMatches = 0;
1474                         /* this only shows up if you have n of the dring patterns filled in */
1475                         ast_verb(3, "Checking %d,%d,%d\n",
1476                                         p->drings.ringnum[counter].ring[0],
1477                                         p->drings.ringnum[counter].ring[1],
1478                                         p->drings.ringnum[counter].ring[2]);
1479                         for (counter1 = 0; counter1 < 3; counter1++) {
1480                                 ast_verb(3, "Ring pattern check range: %d\n", p->drings.ringnum[counter].range);
1481                                 if (p->drings.ringnum[counter].ring[counter1] == -1) {
1482                                         ast_verb(3, "Pattern ignore (-1) detected, so matching pattern %d regardless.\n",
1483                                         ringdata[counter1]);
1484                                         distMatches++;
1485                                 } else if (ringdata[counter1] <= (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range) &&
1486                                                                                 ringdata[counter1] >= (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range)) {
1487                                         ast_verb(3, "Ring pattern matched in range: %d to %d\n",
1488                                         (p->drings.ringnum[counter].ring[counter1] - p->drings.ringnum[counter].range),
1489                                         (p->drings.ringnum[counter].ring[counter1] + p->drings.ringnum[counter].range));
1490                                         distMatches++;
1491                                 }
1492                         }
1493
1494                         if (distMatches == 3) {
1495                                 /* The ring matches, set the context to whatever is for distinctive ring.. */
1496                                 ast_copy_string(p->context, S_OR(p->drings.ringContext[counter].contextData, p->defcontext), sizeof(p->context));
1497                                 ast_channel_context_set(chan, S_OR(p->drings.ringContext[counter].contextData, p->defcontext));
1498                                 ast_verb(3, "Distinctive Ring matched context %s\n",p->context);
1499                                 break;
1500                         }
1501                 }
1502         }
1503         /* Restore linear mode (if appropriate) for Caller*ID processing */
1504         dahdi_setlinear(p->subs[idx].dfd, p->subs[idx].linear);
1505         restore_gains(p);
1506
1507         return 0;
1508 }
1509
1510 static int my_stop_callwait(void *pvt)
1511 {
1512         struct dahdi_pvt *p = pvt;
1513         p->callwaitingrepeat = 0;
1514         p->cidcwexpire = 0;
1515         p->cid_suppress_expire = 0;
1516
1517         return 0;
1518 }
1519
1520 static int send_callerid(struct dahdi_pvt *p);
1521 static int save_conference(struct dahdi_pvt *p);
1522 static int restore_conference(struct dahdi_pvt *p);
1523
1524 static int my_callwait(void *pvt)
1525 {
1526         struct dahdi_pvt *p = pvt;
1527
1528         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
1529         if (p->cidspill) {
1530                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
1531                 ast_free(p->cidspill);
1532         }
1533
1534         /*
1535          * SAS: Subscriber Alert Signal, 440Hz for 300ms
1536          * CAS: CPE Alert Signal, 2130Hz * 2750Hz sine waves
1537          */
1538         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
1539                 return -1;
1540         save_conference(p);
1541         /* Silence */
1542         memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
1543         if (!p->callwaitrings && p->callwaitingcallerid) {
1544                 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
1545                 p->callwaitcas = 1;
1546                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
1547         } else {
1548                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
1549                 p->callwaitcas = 0;
1550                 p->cidlen = 2400 + READ_SIZE * 4;
1551         }
1552         p->cidpos = 0;
1553         send_callerid(p);
1554
1555         return 0;
1556 }
1557
1558 static int my_send_callerid(void *pvt, int cwcid, struct ast_party_caller *caller)
1559 {
1560         struct dahdi_pvt *p = pvt;
1561
1562         ast_debug(2, "Starting cid spill\n");
1563
1564         if (p->cidspill) {
1565                 ast_log(LOG_WARNING, "cidspill already exists??\n");
1566                 ast_free(p->cidspill);
1567         }
1568
1569         if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
1570                 if (cwcid == 0) {
1571                         p->cidlen = ast_callerid_generate(p->cidspill,
1572                                 caller->id.name.str,
1573                                 caller->id.number.str,
1574                                 AST_LAW(p));
1575                 } else {
1576                         ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n",
1577                                 caller->id.name.str, caller->id.number.str);
1578                         p->callwaitcas = 0;
1579                         p->cidcwexpire = 0;
1580                         p->cidlen = ast_callerid_callwaiting_generate(p->cidspill,
1581                                 caller->id.name.str,
1582                                 caller->id.number.str,
1583                                 AST_LAW(p));
1584                         p->cidlen += READ_SIZE * 4;
1585                 }
1586                 p->cidpos = 0;
1587                 p->cid_suppress_expire = 0;
1588                 send_callerid(p);
1589         }
1590         return 0;
1591 }
1592
1593 static int my_dsp_reset_and_flush_digits(void *pvt)
1594 {
1595         struct dahdi_pvt *p = pvt;
1596         if (p->dsp)
1597                 ast_dsp_digitreset(p->dsp);
1598
1599         return 0;
1600 }
1601
1602 static int my_dsp_set_digitmode(void *pvt, enum analog_dsp_digitmode mode)
1603 {
1604         struct dahdi_pvt *p = pvt;
1605
1606         if (p->channel == CHAN_PSEUDO)
1607                 ast_log(LOG_ERROR, "You have assumed incorrectly sir!\n");
1608
1609         if (mode == ANALOG_DIGITMODE_DTMF) {
1610                 /* If we do hardware dtmf, no need for a DSP */
1611                 if (p->hardwaredtmf) {
1612                         if (p->dsp) {
1613                                 ast_dsp_free(p->dsp);
1614                                 p->dsp = NULL;
1615                         }
1616                         return 0;
1617                 }
1618
1619                 if (!p->dsp) {
1620                         p->dsp = ast_dsp_new();
1621                         if (!p->dsp) {
1622                                 ast_log(LOG_ERROR, "Unable to allocate DSP\n");
1623                                 return -1;
1624                         }
1625                 }
1626
1627                 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_DTMF | p->dtmfrelax);
1628         } else if (mode == ANALOG_DIGITMODE_MF) {
1629                 if (!p->dsp) {
1630                         p->dsp = ast_dsp_new();
1631                         if (!p->dsp) {
1632                                 ast_log(LOG_ERROR, "Unable to allocate DSP\n");
1633                                 return -1;
1634                         }
1635                 }
1636                 ast_dsp_set_digitmode(p->dsp, DSP_DIGITMODE_MF | p->dtmfrelax);
1637         }
1638         return 0;
1639 }
1640
1641 static int dahdi_wink(struct dahdi_pvt *p, int index);
1642
1643 static int my_wink(void *pvt, enum analog_sub sub)
1644 {
1645         struct dahdi_pvt *p = pvt;
1646         int index = analogsub_to_dahdisub(sub);
1647         if (index != SUB_REAL) {
1648                 ast_log(LOG_ERROR, "We used a sub other than SUB_REAL (incorrect assumption sir)\n");
1649         }
1650         return dahdi_wink(p, index);
1651 }
1652
1653 static void wakeup_sub(struct dahdi_pvt *p, int a);
1654
1655 static int reset_conf(struct dahdi_pvt *p);
1656
1657 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted);
1658
1659 static void my_handle_dtmf(void *pvt, struct ast_channel *ast, enum analog_sub analog_index, struct ast_frame **dest)
1660 {
1661         struct ast_frame *f = *dest;
1662         struct dahdi_pvt *p = pvt;
1663         int idx = analogsub_to_dahdisub(analog_index);
1664
1665         ast_debug(1, "%s DTMF digit: 0x%02X '%c' on %s\n",
1666                 f->frametype == AST_FRAME_DTMF_BEGIN ? "Begin" : "End",
1667                 (unsigned)f->subclass.integer, f->subclass.integer, ast_channel_name(ast));
1668
1669         if (f->subclass.integer == 'f') {
1670                 if (f->frametype == AST_FRAME_DTMF_END) {
1671                         /* Fax tone -- Handle and return NULL */
1672                         if ((p->callprogress & CALLPROGRESS_FAX) && !p->faxhandled) {
1673                                 /* If faxbuffers are configured, use them for the fax transmission */
1674                                 if (p->usefaxbuffers && !p->bufferoverrideinuse) {
1675                                         struct dahdi_bufferinfo bi = {
1676                                                 .txbufpolicy = p->faxbuf_policy,
1677                                                 .bufsize = p->bufsize,
1678                                                 .numbufs = p->faxbuf_no
1679                                         };
1680                                         int res;
1681
1682                                         if ((res = ioctl(p->subs[idx].dfd, DAHDI_SET_BUFINFO, &bi)) < 0) {
1683                                                 ast_log(LOG_WARNING, "Channel '%s' unable to set buffer policy, reason: %s\n", ast_channel_name(ast), strerror(errno));
1684                                         } else {
1685                                                 p->bufferoverrideinuse = 1;
1686                                         }
1687                                 }
1688                                 p->faxhandled = 1;
1689                                 if (p->dsp) {
1690                                         p->dsp_features &= ~DSP_FEATURE_FAX_DETECT;
1691                                         ast_dsp_set_features(p->dsp, p->dsp_features);
1692                                         ast_debug(1, "Disabling FAX tone detection on %s after tone received\n", ast_channel_name(ast));
1693                                 }
1694                                 if (strcmp(ast_channel_exten(ast), "fax")) {
1695                                         const char *target_context = S_OR(ast_channel_macrocontext(ast), ast_channel_context(ast));
1696
1697                                         /* We need to unlock 'ast' here because ast_exists_extension has the
1698                                          * potential to start autoservice on the channel. Such action is prone
1699                                          * to deadlock.
1700                                          */
1701                                         ast_mutex_unlock(&p->lock);
1702                                         ast_channel_unlock(ast);
1703                                         if (ast_exists_extension(ast, target_context, "fax", 1,
1704                                                 S_COR(ast_channel_caller(ast)->id.number.valid, ast_channel_caller(ast)->id.number.str, NULL))) {
1705                                                 ast_channel_lock(ast);
1706                                                 ast_mutex_lock(&p->lock);
1707                                                 ast_verb(3, "Redirecting %s to fax extension\n", ast_channel_name(ast));
1708                                                 /* Save the DID/DNIS when we transfer the fax call to a "fax" extension */
1709                                                 pbx_builtin_setvar_helper(ast, "FAXEXTEN", ast_channel_exten(ast));
1710                                                 if (ast_async_goto(ast, target_context, "fax", 1))
1711                                                         ast_log(LOG_WARNING, "Failed to async goto '%s' into fax of '%s'\n", ast_channel_name(ast), target_context);
1712                                         } else {
1713                                                 ast_channel_lock(ast);
1714                                                 ast_mutex_lock(&p->lock);
1715                                                 ast_log(LOG_NOTICE, "Fax detected, but no fax extension\n");
1716                                         }
1717                                 } else {
1718                                         ast_debug(1, "Already in a fax extension, not redirecting\n");
1719                                 }
1720                         } else {
1721                                 ast_debug(1, "Fax already handled\n");
1722                         }
1723                         dahdi_confmute(p, 0);
1724                 }
1725                 p->subs[idx].f.frametype = AST_FRAME_NULL;
1726                 p->subs[idx].f.subclass.integer = 0;
1727                 *dest = &p->subs[idx].f;
1728         }
1729 }
1730
1731 static void my_lock_private(void *pvt)
1732 {
1733         struct dahdi_pvt *p = pvt;
1734         ast_mutex_lock(&p->lock);
1735 }
1736
1737 static void my_unlock_private(void *pvt)
1738 {
1739         struct dahdi_pvt *p = pvt;
1740         ast_mutex_unlock(&p->lock);
1741 }
1742
1743 static void my_deadlock_avoidance_private(void *pvt)
1744 {
1745         struct dahdi_pvt *p = pvt;
1746
1747         DEADLOCK_AVOIDANCE(&p->lock);
1748 }
1749
1750 static struct ast_manager_event_blob *dahdichannel_to_ami(struct stasis_message *msg)
1751 {
1752         RAII_VAR(struct ast_str *, channel_string, NULL, ast_free);
1753         struct ast_channel_blob *obj = stasis_message_data(msg);
1754         struct ast_json *span, *channel;
1755
1756         channel_string = ast_manager_build_channel_state_string(obj->snapshot);
1757         if (!channel_string) {
1758                 return NULL;
1759         }
1760
1761         span = ast_json_object_get(obj->blob, "span");
1762         channel = ast_json_object_get(obj->blob, "channel");
1763
1764         return ast_manager_event_blob_create(EVENT_FLAG_CALL, "DAHDIChannel",
1765                 "%s"
1766                 "DAHDISpan: %u\r\n"
1767                 "DAHDIChannel: %s\r\n",
1768                 ast_str_buffer(channel_string),
1769                 (unsigned int)ast_json_integer_get(span),
1770                 ast_json_string_get(channel));
1771 }
1772
1773 STASIS_MESSAGE_TYPE_DEFN_LOCAL(dahdichannel_type,
1774         .to_ami = dahdichannel_to_ami,
1775         );
1776
1777 /*! \brief Sends a DAHDIChannel channel blob used to produce DAHDIChannel AMI messages */
1778 static void publish_dahdichannel(struct ast_channel *chan, int span, const char *dahdi_channel)
1779 {
1780         RAII_VAR(struct ast_json *, blob, NULL, ast_json_unref);
1781
1782         ast_assert(dahdi_channel != NULL);
1783
1784         blob = ast_json_pack("{s: i, s: s}",
1785                 "span", span,
1786                 "channel", dahdi_channel);
1787         if (!blob) {
1788                 return;
1789         }
1790
1791         ast_channel_lock(chan);
1792         ast_channel_publish_blob(chan, dahdichannel_type(), blob);
1793         ast_channel_unlock(chan);
1794 }
1795
1796 /*!
1797  * \internal
1798  * \brief Post an AMI DAHDI channel association event.
1799  * \since 1.8
1800  *
1801  * \param p DAHDI private pointer
1802  * \param chan Channel associated with the private pointer
1803  *
1804  * \return Nothing
1805  */
1806 static void dahdi_ami_channel_event(struct dahdi_pvt *p, struct ast_channel *chan)
1807 {
1808         char ch_name[20];
1809
1810         if (p->channel < CHAN_PSEUDO) {
1811                 /* No B channel */
1812                 snprintf(ch_name, sizeof(ch_name), "no-media (%d)", p->channel);
1813         } else if (p->channel == CHAN_PSEUDO) {
1814                 /* Pseudo channel */
1815                 strcpy(ch_name, "pseudo");
1816         } else {
1817                 /* Real channel */
1818                 snprintf(ch_name, sizeof(ch_name), "%d", p->channel);
1819         }
1820         publish_dahdichannel(chan, p->span, ch_name);
1821 }
1822
1823 #ifdef HAVE_PRI
1824 /*!
1825  * \internal
1826  * \brief Post an AMI DAHDI channel association event.
1827  * \since 1.8
1828  *
1829  * \param pvt DAHDI private pointer
1830  * \param chan Channel associated with the private pointer
1831  *
1832  * \return Nothing
1833  */
1834 static void my_ami_channel_event(void *pvt, struct ast_channel *chan)
1835 {
1836         struct dahdi_pvt *p = pvt;
1837
1838         dahdi_ami_channel_event(p, chan);
1839 }
1840 #endif
1841
1842 /* linear_mode = 0 - turn linear mode off, >0 - turn linear mode on
1843 *       returns the last value of the linear setting
1844 */
1845 static int my_set_linear_mode(void *pvt, enum analog_sub sub, int linear_mode)
1846 {
1847         struct dahdi_pvt *p = pvt;
1848         int oldval;
1849         int idx = analogsub_to_dahdisub(sub);
1850
1851         dahdi_setlinear(p->subs[idx].dfd, linear_mode);
1852         oldval = p->subs[idx].linear;
1853         p->subs[idx].linear = linear_mode ? 1 : 0;
1854         return oldval;
1855 }
1856
1857 static void my_set_inthreeway(void *pvt, enum analog_sub sub, int inthreeway)
1858 {
1859         struct dahdi_pvt *p = pvt;
1860         int idx = analogsub_to_dahdisub(sub);
1861
1862         p->subs[idx].inthreeway = inthreeway;
1863 }
1864
1865 static int get_alarms(struct dahdi_pvt *p);
1866 static void handle_alarms(struct dahdi_pvt *p, int alms);
1867 static void my_get_and_handle_alarms(void *pvt)
1868 {
1869         int res;
1870         struct dahdi_pvt *p = pvt;
1871
1872         res = get_alarms(p);
1873         handle_alarms(p, res);
1874 }
1875
1876 static void *my_get_sigpvt_bridged_channel(struct ast_channel *chan)
1877 {
1878         RAII_VAR(struct ast_channel *, bridged, ast_channel_bridge_peer(chan), ast_channel_cleanup);
1879
1880         if (bridged && ast_channel_tech(bridged) == &dahdi_tech) {
1881                 struct dahdi_pvt *p = ast_channel_tech_pvt(bridged);
1882
1883                 if (dahdi_analog_lib_handles(p->sig, p->radio, p->oprmode)) {
1884                         return p->sig_pvt;
1885                 }
1886         }
1887         return NULL;
1888 }
1889
1890 static int my_get_sub_fd(void *pvt, enum analog_sub sub)
1891 {
1892         struct dahdi_pvt *p = pvt;
1893         int dahdi_sub = analogsub_to_dahdisub(sub);
1894         return p->subs[dahdi_sub].dfd;
1895 }
1896
1897 static void my_set_cadence(void *pvt, int *cid_rings, struct ast_channel *ast)
1898 {
1899         struct dahdi_pvt *p = pvt;
1900
1901         /* Choose proper cadence */
1902         if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
1903                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
1904                         ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast_channel_name(ast), strerror(errno));
1905                 *cid_rings = cidrings[p->distinctivering - 1];
1906         } else {
1907                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
1908                         ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast_channel_name(ast), strerror(errno));
1909                 *cid_rings = p->sendcalleridafter;
1910         }
1911 }
1912
1913 static void my_set_alarm(void *pvt, int in_alarm)
1914 {
1915         struct dahdi_pvt *p = pvt;
1916
1917         p->inalarm = in_alarm;
1918 }
1919
1920 static void my_set_dialing(void *pvt, int is_dialing)
1921 {
1922         struct dahdi_pvt *p = pvt;
1923
1924         p->dialing = is_dialing;
1925 }
1926
1927 static void my_set_outgoing(void *pvt, int is_outgoing)
1928 {
1929         struct dahdi_pvt *p = pvt;
1930
1931         p->outgoing = is_outgoing;
1932 }
1933
1934 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1935 static void my_set_digital(void *pvt, int is_digital)
1936 {
1937         struct dahdi_pvt *p = pvt;
1938
1939         p->digital = is_digital;
1940 }
1941 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
1942
1943 #if defined(HAVE_SS7)
1944 static void my_set_inservice(void *pvt, int is_inservice)
1945 {
1946         struct dahdi_pvt *p = pvt;
1947
1948         p->inservice = is_inservice;
1949 }
1950 #endif  /* defined(HAVE_SS7) */
1951
1952 #if defined(HAVE_SS7)
1953 static void my_set_locallyblocked(void *pvt, int is_blocked)
1954 {
1955         struct dahdi_pvt *p = pvt;
1956
1957         p->locallyblocked = is_blocked;
1958 }
1959 #endif  /* defined(HAVE_SS7) */
1960
1961 #if defined(HAVE_SS7)
1962 static void my_set_remotelyblocked(void *pvt, int is_blocked)
1963 {
1964         struct dahdi_pvt *p = pvt;
1965
1966         p->remotelyblocked = is_blocked;
1967 }
1968 #endif  /* defined(HAVE_SS7) */
1969
1970 static void my_set_ringtimeout(void *pvt, int ringt)
1971 {
1972         struct dahdi_pvt *p = pvt;
1973         p->ringt = ringt;
1974 }
1975
1976 static void my_set_waitingfordt(void *pvt, struct ast_channel *ast)
1977 {
1978         struct dahdi_pvt *p = pvt;
1979
1980         if (p->waitfordialtone && CANPROGRESSDETECT(p) && p->dsp) {
1981                 ast_debug(1, "Defer dialing for %dms or dialtone\n", p->waitfordialtone);
1982                 gettimeofday(&p->waitingfordt, NULL);
1983                 ast_setstate(ast, AST_STATE_OFFHOOK);
1984         }
1985 }
1986
1987 static int my_check_waitingfordt(void *pvt)
1988 {
1989         struct dahdi_pvt *p = pvt;
1990
1991         if (p->waitingfordt.tv_sec) {
1992                 return 1;
1993         }
1994
1995         return 0;
1996 }
1997
1998 static void my_set_confirmanswer(void *pvt, int flag)
1999 {
2000         struct dahdi_pvt *p = pvt;
2001         p->confirmanswer = flag;
2002 }
2003
2004 static int my_check_confirmanswer(void *pvt)
2005 {
2006         struct dahdi_pvt *p = pvt;
2007         if (p->confirmanswer) {
2008                 return 1;
2009         }
2010
2011         return 0;
2012 }
2013
2014 static void my_set_callwaiting(void *pvt, int callwaiting_enable)
2015 {
2016         struct dahdi_pvt *p = pvt;
2017
2018         p->callwaiting = callwaiting_enable;
2019 }
2020
2021 static void my_cancel_cidspill(void *pvt)
2022 {
2023         struct dahdi_pvt *p = pvt;
2024
2025         ast_free(p->cidspill);
2026         p->cidspill = NULL;
2027         restore_conference(p);
2028 }
2029
2030 static int my_confmute(void *pvt, int mute)
2031 {
2032         struct dahdi_pvt *p = pvt;
2033         return dahdi_confmute(p, mute);
2034 }
2035
2036 static void my_set_pulsedial(void *pvt, int flag)
2037 {
2038         struct dahdi_pvt *p = pvt;
2039         p->pulsedial = flag;
2040 }
2041
2042 static void my_set_new_owner(void *pvt, struct ast_channel *new_owner)
2043 {
2044         struct dahdi_pvt *p = pvt;
2045
2046         p->owner = new_owner;
2047 }
2048
2049 static const char *my_get_orig_dialstring(void *pvt)
2050 {
2051         struct dahdi_pvt *p = pvt;
2052
2053         return p->dialstring;
2054 }
2055
2056 static void my_increase_ss_count(void)
2057 {
2058         ast_mutex_lock(&ss_thread_lock);
2059         ss_thread_count++;
2060         ast_mutex_unlock(&ss_thread_lock);
2061 }
2062
2063 static void my_decrease_ss_count(void)
2064 {
2065         ast_mutex_lock(&ss_thread_lock);
2066         ss_thread_count--;
2067         ast_cond_signal(&ss_thread_complete);
2068         ast_mutex_unlock(&ss_thread_lock);
2069 }
2070
2071 static void my_all_subchannels_hungup(void *pvt)
2072 {
2073         struct dahdi_pvt *p = pvt;
2074         int res, law;
2075
2076         p->faxhandled = 0;
2077         p->didtdd = 0;
2078
2079         if (p->dsp) {
2080                 ast_dsp_free(p->dsp);
2081                 p->dsp = NULL;
2082         }
2083
2084         p->law = p->law_default;
2085         law = p->law_default;
2086         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETLAW, &law);
2087         if (res < 0)
2088                 ast_log(LOG_WARNING, "Unable to set law on channel %d to default: %s\n", p->channel, strerror(errno));
2089
2090         dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
2091
2092 #if 1
2093         {
2094         int i;
2095         p->owner = NULL;
2096         /* Cleanup owners here */
2097         for (i = 0; i < 3; i++) {
2098                 p->subs[i].owner = NULL;
2099         }
2100         }
2101 #endif
2102
2103         reset_conf(p);
2104         if (num_restart_pending == 0) {
2105                 restart_monitor();
2106         }
2107 }
2108
2109 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index);
2110
2111 static int my_conf_del(void *pvt, enum analog_sub sub)
2112 {
2113         struct dahdi_pvt *p = pvt;
2114         int x = analogsub_to_dahdisub(sub);
2115
2116         return conf_del(p, &p->subs[x], x);
2117 }
2118
2119 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int index, int slavechannel);
2120
2121 static int my_conf_add(void *pvt, enum analog_sub sub)
2122 {
2123         struct dahdi_pvt *p = pvt;
2124         int x = analogsub_to_dahdisub(sub);
2125
2126         return conf_add(p, &p->subs[x], x, 0);
2127 }
2128
2129 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out);
2130
2131 static int my_complete_conference_update(void *pvt, int needconference)
2132 {
2133         struct dahdi_pvt *p = pvt;
2134         int needconf = needconference;
2135         int x;
2136         int useslavenative;
2137         struct dahdi_pvt *slave = NULL;
2138
2139         useslavenative = isslavenative(p, &slave);
2140
2141         /* If we have a slave, add him to our conference now. or DAX
2142            if this is slave native */
2143         for (x = 0; x < MAX_SLAVES; x++) {
2144                 if (p->slaves[x]) {
2145                         if (useslavenative)
2146                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
2147                         else {
2148                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
2149                                 needconf++;
2150                         }
2151                 }
2152         }
2153         /* If we're supposed to be in there, do so now */
2154         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
2155                 if (useslavenative)
2156                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
2157                 else {
2158                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
2159                         needconf++;
2160                 }
2161         }
2162         /* If we have a master, add ourselves to his conference */
2163         if (p->master) {
2164                 if (isslavenative(p->master, NULL)) {
2165                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
2166                 } else {
2167                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
2168                 }
2169         }
2170         if (!needconf) {
2171                 /* Nobody is left (or should be left) in our conference.
2172                    Kill it. */
2173                 p->confno = -1;
2174         }
2175
2176         return 0;
2177 }
2178
2179 static int check_for_conference(struct dahdi_pvt *p);
2180
2181 static int my_check_for_conference(void *pvt)
2182 {
2183         struct dahdi_pvt *p = pvt;
2184         return check_for_conference(p);
2185 }
2186
2187 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)
2188 {
2189         struct dahdi_pvt *p = pvt;
2190         int da, db;
2191         int tchan;
2192         int tinthreeway;
2193
2194         da = analogsub_to_dahdisub(a);
2195         db = analogsub_to_dahdisub(b);
2196
2197         tchan = p->subs[da].chan;
2198         p->subs[da].chan = p->subs[db].chan;
2199         p->subs[db].chan = tchan;
2200
2201         tinthreeway = p->subs[da].inthreeway;
2202         p->subs[da].inthreeway = p->subs[db].inthreeway;
2203         p->subs[db].inthreeway = tinthreeway;
2204
2205         p->subs[da].owner = ast_a;
2206         p->subs[db].owner = ast_b;
2207
2208         if (ast_a)
2209                 ast_channel_set_fd(ast_a, 0, p->subs[da].dfd);
2210         if (ast_b)
2211                 ast_channel_set_fd(ast_b, 0, p->subs[db].dfd);
2212
2213         wakeup_sub(p, a);
2214         wakeup_sub(p, b);
2215
2216         return;
2217 }
2218
2219 /*!
2220  * \internal
2221  * \brief performs duties of dahdi_new, but also removes and possibly unbinds (if callid_created is 1) before returning
2222  * \note this variant of dahdi should only be used in conjunction with ast_callid_threadstorage_auto()
2223  *
2224  * \param callid_created value returned from ast_callid_threadstorage_auto()
2225  */
2226 static struct ast_channel *dahdi_new_callid_clean(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, struct ast_callid *callid, int callid_created);
2227
2228 static struct ast_channel *dahdi_new(struct dahdi_pvt *i, int state, int startpbx, int idx, int law, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor, struct ast_callid *callid);
2229
2230 static struct ast_channel *my_new_analog_ast_channel(void *pvt, int state, int startpbx, enum analog_sub sub, const struct ast_channel *requestor)
2231 {
2232         struct ast_callid *callid = NULL;
2233         int callid_created = ast_callid_threadstorage_auto(&callid);
2234         struct dahdi_pvt *p = pvt;
2235         int dsub = analogsub_to_dahdisub(sub);
2236
2237         return dahdi_new_callid_clean(p, state, startpbx, dsub, 0, NULL, requestor, callid, callid_created);
2238 }
2239
2240 #if defined(HAVE_PRI) || defined(HAVE_SS7)
2241 static int dahdi_setlaw(int dfd, int law)
2242 {
2243         int res;
2244         res = ioctl(dfd, DAHDI_SETLAW, &law);
2245         if (res)
2246                 return res;
2247         return 0;
2248 }
2249 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
2250
2251 #if defined(HAVE_PRI)
2252 static struct ast_channel *my_new_pri_ast_channel(void *pvt, int state,
2253         enum sig_pri_law law, char *exten, const struct ast_assigned_ids *assignedids,
2254         const struct ast_channel *requestor)
2255 {
2256         struct dahdi_pvt *p = pvt;
2257         int audio;
2258         int newlaw = -1;
2259         struct ast_callid *callid = NULL;
2260         int callid_created = ast_callid_threadstorage_auto(&callid);
2261
2262         switch (p->sig) {
2263         case SIG_PRI_LIB_HANDLE_CASES:
2264                 if (((struct sig_pri_chan *) p->sig_pvt)->no_b_channel) {
2265                         /* PRI nobch pseudo channel.  Does not handle ioctl(DAHDI_AUDIOMODE) */
2266                         break;
2267                 }
2268                 /* Fall through */
2269         default:
2270                 /* Set to audio mode at this point */
2271                 audio = 1;
2272                 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1) {
2273                         ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
2274                                 p->channel, audio, strerror(errno));
2275                 }
2276                 break;
2277         }
2278
2279         if (law != SIG_PRI_DEFLAW) {
2280                 dahdi_setlaw(p->subs[SUB_REAL].dfd, (law == SIG_PRI_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
2281         }
2282
2283         ast_copy_string(p->exten, exten, sizeof(p->exten));
2284
2285         switch (law) {
2286                 case SIG_PRI_DEFLAW:
2287                         newlaw = 0;
2288                         break;
2289                 case SIG_PRI_ALAW:
2290                         newlaw = DAHDI_LAW_ALAW;
2291                         break;
2292                 case SIG_PRI_ULAW:
2293                         newlaw = DAHDI_LAW_MULAW;
2294                         break;
2295         }
2296
2297         return dahdi_new_callid_clean(p, state, 0, SUB_REAL, newlaw, assignedids, requestor, callid, callid_created);
2298 }
2299 #endif  /* defined(HAVE_PRI) */
2300
2301 static int set_actual_gain(int fd, float rxgain, float txgain, float rxdrc, float txdrc, int law);
2302
2303 #if defined(HAVE_PRI) || defined(HAVE_SS7)
2304 /*!
2305  * \internal
2306  * \brief Open the PRI/SS7 channel media path.
2307  * \since 1.8
2308  *
2309  * \param p Channel private control structure.
2310  *
2311  * \return Nothing
2312  */
2313 static void my_pri_ss7_open_media(void *p)
2314 {
2315         struct dahdi_pvt *pvt = p;
2316         int res;
2317         int dfd;
2318         int set_val;
2319
2320         dfd = pvt->subs[SUB_REAL].dfd;
2321
2322         /* Open the media path. */
2323         set_val = 1;
2324         res = ioctl(dfd, DAHDI_AUDIOMODE, &set_val);
2325         if (res < 0) {
2326                 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n",
2327                         pvt->channel, strerror(errno));
2328         }
2329
2330         /* Set correct companding law for this call. */
2331         res = dahdi_setlaw(dfd, pvt->law);
2332         if (res < 0) {
2333                 ast_log(LOG_WARNING, "Unable to set law on channel %d\n", pvt->channel);
2334         }
2335
2336         /* Set correct gain for this call. */
2337         if (pvt->digital) {
2338                 res = set_actual_gain(dfd, 0, 0, pvt->rxdrc, pvt->txdrc, pvt->law);
2339         } else {
2340                 res = set_actual_gain(dfd, pvt->rxgain, pvt->txgain, pvt->rxdrc, pvt->txdrc,
2341                         pvt->law);
2342         }
2343         if (res < 0) {
2344                 ast_log(LOG_WARNING, "Unable to set gains on channel %d\n", pvt->channel);
2345         }
2346
2347         if (pvt->dsp_features && pvt->dsp) {
2348                 ast_dsp_set_features(pvt->dsp, pvt->dsp_features);
2349                 pvt->dsp_features = 0;
2350         }
2351 }
2352 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
2353
2354 #if defined(HAVE_PRI)
2355 /*!
2356  * \internal
2357  * \brief Ask DAHDI to dial the given dial string.
2358  * \since 1.8.11
2359  *
2360  * \param p Channel private control structure.
2361  * \param dial_string String to pass to DAHDI to dial.
2362  *
2363  * \note The channel private lock needs to be held when calling.
2364  *
2365  * \return Nothing
2366  */
2367 static void my_pri_dial_digits(void *p, const char *dial_string)
2368 {
2369         char dial_str[DAHDI_MAX_DTMF_BUF];
2370         struct dahdi_pvt *pvt = p;
2371         int res;
2372
2373         snprintf(dial_str, sizeof(dial_str), "T%s", dial_string);
2374         res = dahdi_dial_str(pvt, DAHDI_DIAL_OP_APPEND, dial_str);
2375         if (!res) {
2376                 pvt->dialing = 1;
2377         }
2378 }
2379 #endif  /* defined(HAVE_PRI) */
2380
2381 static int unalloc_sub(struct dahdi_pvt *p, int x);
2382
2383 static int my_unallocate_sub(void *pvt, enum analog_sub analogsub)
2384 {
2385         struct dahdi_pvt *p = pvt;
2386
2387         return unalloc_sub(p, analogsub_to_dahdisub(analogsub));
2388 }
2389
2390 static int alloc_sub(struct dahdi_pvt *p, int x);
2391
2392 static int my_allocate_sub(void *pvt, enum analog_sub analogsub)
2393 {
2394         struct dahdi_pvt *p = pvt;
2395
2396         return alloc_sub(p, analogsub_to_dahdisub(analogsub));
2397 }
2398
2399 static int has_voicemail(struct dahdi_pvt *p);
2400
2401 static int my_has_voicemail(void *pvt)
2402 {
2403         struct dahdi_pvt *p = pvt;
2404
2405         return has_voicemail(p);
2406 }
2407
2408 static int my_play_tone(void *pvt, enum analog_sub sub, enum analog_tone tone)
2409 {
2410         struct dahdi_pvt *p = pvt;
2411         int index;
2412
2413         index = analogsub_to_dahdisub(sub);
2414
2415         return tone_zone_play_tone(p->subs[index].dfd, analog_tone_to_dahditone(tone));
2416 }
2417
2418 static enum analog_event dahdievent_to_analogevent(int event)
2419 {
2420         enum analog_event res;
2421
2422         switch (event) {
2423         case DAHDI_EVENT_ONHOOK:
2424                 res = ANALOG_EVENT_ONHOOK;
2425                 break;
2426         case DAHDI_EVENT_RINGOFFHOOK:
2427                 res = ANALOG_EVENT_RINGOFFHOOK;
2428                 break;
2429         case DAHDI_EVENT_WINKFLASH:
2430                 res = ANALOG_EVENT_WINKFLASH;
2431                 break;
2432         case DAHDI_EVENT_ALARM:
2433                 res = ANALOG_EVENT_ALARM;
2434                 break;
2435         case DAHDI_EVENT_NOALARM:
2436                 res = ANALOG_EVENT_NOALARM;
2437                 break;
2438         case DAHDI_EVENT_DIALCOMPLETE:
2439                 res = ANALOG_EVENT_DIALCOMPLETE;
2440                 break;
2441         case DAHDI_EVENT_RINGERON:
2442                 res = ANALOG_EVENT_RINGERON;
2443                 break;
2444         case DAHDI_EVENT_RINGEROFF:
2445                 res = ANALOG_EVENT_RINGEROFF;
2446                 break;
2447         case DAHDI_EVENT_HOOKCOMPLETE:
2448                 res = ANALOG_EVENT_HOOKCOMPLETE;
2449                 break;
2450         case DAHDI_EVENT_PULSE_START:
2451                 res = ANALOG_EVENT_PULSE_START;
2452                 break;
2453         case DAHDI_EVENT_POLARITY:
2454                 res = ANALOG_EVENT_POLARITY;
2455                 break;
2456         case DAHDI_EVENT_RINGBEGIN:
2457                 res = ANALOG_EVENT_RINGBEGIN;
2458                 break;
2459         case DAHDI_EVENT_EC_DISABLED:
2460                 res = ANALOG_EVENT_EC_DISABLED;
2461                 break;
2462         case DAHDI_EVENT_REMOVED:
2463                 res = ANALOG_EVENT_REMOVED;
2464                 break;
2465         case DAHDI_EVENT_NEONMWI_ACTIVE:
2466                 res = ANALOG_EVENT_NEONMWI_ACTIVE;
2467                 break;
2468         case DAHDI_EVENT_NEONMWI_INACTIVE:
2469                 res = ANALOG_EVENT_NEONMWI_INACTIVE;
2470                 break;
2471 #ifdef HAVE_DAHDI_ECHOCANCEL_FAX_MODE
2472         case DAHDI_EVENT_TX_CED_DETECTED:
2473                 res = ANALOG_EVENT_TX_CED_DETECTED;
2474                 break;
2475         case DAHDI_EVENT_RX_CED_DETECTED:
2476                 res = ANALOG_EVENT_RX_CED_DETECTED;
2477                 break;
2478         case DAHDI_EVENT_EC_NLP_DISABLED:
2479                 res = ANALOG_EVENT_EC_NLP_DISABLED;
2480                 break;
2481         case DAHDI_EVENT_EC_NLP_ENABLED:
2482                 res = ANALOG_EVENT_EC_NLP_ENABLED;
2483                 break;
2484 #endif
2485         case DAHDI_EVENT_PULSEDIGIT:
2486                 res = ANALOG_EVENT_PULSEDIGIT;
2487                 break;
2488         case DAHDI_EVENT_DTMFDOWN:
2489                 res = ANALOG_EVENT_DTMFDOWN;
2490                 break;
2491         case DAHDI_EVENT_DTMFUP:
2492                 res = ANALOG_EVENT_DTMFUP;
2493                 break;
2494         default:
2495                 switch(event & 0xFFFF0000) {
2496                 case DAHDI_EVENT_PULSEDIGIT:
2497                 case DAHDI_EVENT_DTMFDOWN:
2498                 case DAHDI_EVENT_DTMFUP:
2499                         /* The event includes a digit number in the low word.
2500                          * Converting it to a 'enum analog_event' would remove
2501                          * that information. Thus it is returned as-is.
2502                          */
2503                         return event;
2504                 }
2505
2506                 res = ANALOG_EVENT_ERROR;
2507                 break;
2508         }
2509
2510         return res;
2511 }
2512
2513 static inline int dahdi_wait_event(int fd);
2514
2515 static int my_wait_event(void *pvt)
2516 {
2517         struct dahdi_pvt *p = pvt;
2518
2519         return dahdi_wait_event(p->subs[SUB_REAL].dfd);
2520 }
2521
2522 static int my_get_event(void *pvt)
2523 {
2524         struct dahdi_pvt *p = pvt;
2525         int res;
2526
2527         if (p->fake_event) {
2528                 res = p->fake_event;
2529                 p->fake_event = 0;
2530         } else
2531                 res = dahdi_get_event(p->subs[SUB_REAL].dfd);
2532
2533         return dahdievent_to_analogevent(res);
2534 }
2535
2536 static int my_is_off_hook(void *pvt)
2537 {
2538         struct dahdi_pvt *p = pvt;
2539         int res;
2540         struct dahdi_params par;
2541
2542         memset(&par, 0, sizeof(par));
2543
2544         if (p->subs[SUB_REAL].dfd > -1)
2545                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GET_PARAMS, &par);
2546         else {
2547                 /* Assume not off hook on CVRS */
2548                 res = 0;
2549                 par.rxisoffhook = 0;
2550         }
2551         if (res) {
2552                 ast_log(LOG_WARNING, "Unable to check hook state on channel %d: %s\n", p->channel, strerror(errno));
2553         }
2554
2555         if ((p->sig == SIG_FXSKS) || (p->sig == SIG_FXSGS)) {
2556                 /* When "onhook" that means no battery on the line, and thus
2557                 it is out of service..., if it's on a TDM card... If it's a channel
2558                 bank, there is no telling... */
2559                 return (par.rxbits > -1) || par.rxisoffhook;
2560         }
2561
2562         return par.rxisoffhook;
2563 }
2564
2565 static int my_set_echocanceller(void *pvt, int enable)
2566 {
2567         struct dahdi_pvt *p = pvt;
2568
2569         if (enable)
2570                 dahdi_ec_enable(p);
2571         else
2572                 dahdi_ec_disable(p);
2573
2574         return 0;
2575 }
2576
2577 static int dahdi_ring_phone(struct dahdi_pvt *p);
2578
2579 static int my_ring(void *pvt)
2580 {
2581         struct dahdi_pvt *p = pvt;
2582
2583         return dahdi_ring_phone(p);
2584 }
2585
2586 static int my_flash(void *pvt)
2587 {
2588         struct dahdi_pvt *p = pvt;
2589         int func = DAHDI_FLASH;
2590         return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &func);
2591 }
2592
2593 static inline int dahdi_set_hook(int fd, int hs);
2594
2595 static int my_off_hook(void *pvt)
2596 {
2597         struct dahdi_pvt *p = pvt;
2598         return dahdi_set_hook(p->subs[SUB_REAL].dfd, DAHDI_OFFHOOK);
2599 }
2600
2601 static void my_set_needringing(void *pvt, int value)
2602 {
2603         struct dahdi_pvt *p = pvt;
2604         p->subs[SUB_REAL].needringing = value;
2605 }
2606
2607 static void my_set_polarity(void *pvt, int value)
2608 {
2609         struct dahdi_pvt *p = pvt;
2610
2611         if (p->channel == CHAN_PSEUDO) {
2612                 return;
2613         }
2614         p->polarity = value;
2615         ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETPOLARITY, &value);
2616 }
2617
2618 static void my_start_polarityswitch(void *pvt)
2619 {
2620         struct dahdi_pvt *p = pvt;
2621
2622         if (p->answeronpolarityswitch || p->hanguponpolarityswitch) {
2623                 my_set_polarity(pvt, 0);
2624         }
2625 }
2626
2627 static void my_answer_polarityswitch(void *pvt)
2628 {
2629         struct dahdi_pvt *p = pvt;
2630
2631         if (!p->answeronpolarityswitch) {
2632                 return;
2633         }
2634
2635         my_set_polarity(pvt, 1);
2636 }
2637
2638 static void my_hangup_polarityswitch(void *pvt)
2639 {
2640         struct dahdi_pvt *p = pvt;
2641
2642         if (!p->hanguponpolarityswitch) {
2643                 return;
2644         }
2645
2646         if (p->answeronpolarityswitch) {
2647                 my_set_polarity(pvt, 0);
2648         } else {
2649                 my_set_polarity(pvt, 1);
2650         }
2651 }
2652
2653 static int my_start(void *pvt)
2654 {
2655         struct dahdi_pvt *p = pvt;
2656         int x = DAHDI_START;
2657
2658         return ioctl(p->subs[SUB_REAL].dfd, DAHDI_HOOK, &x);
2659 }
2660
2661 static int my_dial_digits(void *pvt, enum analog_sub sub, struct analog_dialoperation *dop)
2662 {
2663         struct dahdi_pvt *p = pvt;
2664
2665         if (dop->op != ANALOG_DIAL_OP_REPLACE) {
2666                 ast_log(LOG_ERROR, "Fix the dial_digits callback!\n");
2667                 return -1;
2668         }
2669
2670         if (sub != ANALOG_SUB_REAL) {
2671                 ast_log(LOG_ERROR, "Trying to dial_digits '%s' on channel %d subchannel %u\n",
2672                         dop->dialstr, p->channel, sub);
2673                 return -1;
2674         }
2675
2676         return dahdi_dial_str(p, DAHDI_DIAL_OP_REPLACE, dop->dialstr);
2677 }
2678
2679 static void dahdi_train_ec(struct dahdi_pvt *p);
2680
2681 static int my_train_echocanceller(void *pvt)
2682 {
2683         struct dahdi_pvt *p = pvt;
2684
2685         dahdi_train_ec(p);
2686
2687         return 0;
2688 }
2689
2690 static int my_is_dialing(void *pvt, enum analog_sub sub)
2691 {
2692         struct dahdi_pvt *p = pvt;
2693         int index;
2694         int x;
2695
2696         index = analogsub_to_dahdisub(sub);
2697
2698         if (ioctl(p->subs[index].dfd, DAHDI_DIALING, &x)) {
2699                 ast_debug(1, "DAHDI_DIALING ioctl failed!\n");
2700                 return -1;
2701         }
2702
2703         return x;
2704 }
2705
2706 static int my_on_hook(void *pvt)
2707 {
2708         struct dahdi_pvt *p = pvt;
2709         return dahdi_set_hook(p->subs[ANALOG_SUB_REAL].dfd, DAHDI_ONHOOK);
2710 }
2711
2712 #if defined(HAVE_PRI)
2713 static void my_pri_fixup_chans(void *chan_old, void *chan_new)
2714 {
2715         struct dahdi_pvt *old_chan = chan_old;
2716         struct dahdi_pvt *new_chan = chan_new;
2717
2718         new_chan->owner = old_chan->owner;
2719         old_chan->owner = NULL;
2720         if (new_chan->owner) {
2721                 ast_channel_tech_pvt_set(new_chan->owner, new_chan);
2722                 ast_channel_internal_fd_set(new_chan->owner, 0, new_chan->subs[SUB_REAL].dfd);
2723                 new_chan->subs[SUB_REAL].owner = old_chan->subs[SUB_REAL].owner;
2724                 old_chan->subs[SUB_REAL].owner = NULL;
2725         }
2726         /* Copy any DSP that may be present */
2727         new_chan->dsp = old_chan->dsp;
2728         new_chan->dsp_features = old_chan->dsp_features;
2729         old_chan->dsp = NULL;
2730         old_chan->dsp_features = 0;
2731
2732         /* Transfer flags from the old channel. */
2733         new_chan->dialing = old_chan->dialing;
2734         new_chan->digital = old_chan->digital;
2735         new_chan->outgoing = old_chan->outgoing;
2736         old_chan->dialing = 0;
2737         old_chan->digital = 0;
2738         old_chan->outgoing = 0;
2739
2740         /* More stuff to transfer to the new channel. */
2741         new_chan->law = old_chan->law;
2742         strcpy(new_chan->dialstring, old_chan->dialstring);
2743 }
2744 #endif  /* defined(HAVE_PRI) */
2745
2746 #if defined(HAVE_PRI)
2747 static int sig_pri_tone_to_dahditone(enum sig_pri_tone tone)
2748 {
2749         switch (tone) {
2750         case SIG_PRI_TONE_RINGTONE:
2751                 return DAHDI_TONE_RINGTONE;
2752         case SIG_PRI_TONE_STUTTER:
2753                 return DAHDI_TONE_STUTTER;
2754         case SIG_PRI_TONE_CONGESTION:
2755                 return DAHDI_TONE_CONGESTION;
2756         case SIG_PRI_TONE_DIALTONE:
2757                 return DAHDI_TONE_DIALTONE;
2758         case SIG_PRI_TONE_DIALRECALL:
2759                 return DAHDI_TONE_DIALRECALL;
2760         case SIG_PRI_TONE_INFO:
2761                 return DAHDI_TONE_INFO;
2762         case SIG_PRI_TONE_BUSY:
2763                 return DAHDI_TONE_BUSY;
2764         default:
2765                 return -1;
2766         }
2767 }
2768 #endif  /* defined(HAVE_PRI) */
2769
2770 #if defined(HAVE_PRI)
2771 static void my_handle_dchan_exception(struct sig_pri_span *pri, int index)
2772 {
2773         int x;
2774
2775         ioctl(pri->fds[index], DAHDI_GETEVENT, &x);
2776         switch (x) {
2777         case DAHDI_EVENT_NONE:
2778                 break;
2779         case DAHDI_EVENT_ALARM:
2780         case DAHDI_EVENT_NOALARM:
2781                 if (sig_pri_is_alarm_ignored(pri)) {
2782                         break;
2783                 }
2784                 /* Fall through */
2785         default:
2786                 ast_log(LOG_NOTICE, "Got DAHDI event: %s (%d) on D-channel of span %d\n",
2787                         event2str(x), x, pri->span);
2788                 break;
2789         }
2790         /* Keep track of alarm state */
2791         switch (x) {
2792         case DAHDI_EVENT_ALARM:
2793                 pri_event_alarm(pri, index, 0);
2794                 break;
2795         case DAHDI_EVENT_NOALARM:
2796                 pri_event_noalarm(pri, index, 0);
2797                 break;
2798         case DAHDI_EVENT_REMOVED:
2799                 pri_queue_for_destruction(pri);
2800                 break;
2801         default:
2802                 break;
2803         }
2804 }
2805 #endif  /* defined(HAVE_PRI) */
2806
2807 #if defined(HAVE_PRI)
2808 static int my_pri_play_tone(void *pvt, enum sig_pri_tone tone)
2809 {
2810         struct dahdi_pvt *p = pvt;
2811
2812         return tone_zone_play_tone(p->subs[SUB_REAL].dfd, sig_pri_tone_to_dahditone(tone));
2813 }
2814 #endif  /* defined(HAVE_PRI) */
2815
2816 #if defined(HAVE_PRI) || defined(HAVE_SS7)
2817 /*!
2818  * \internal
2819  * \brief Set the caller id information.
2820  * \since 1.8
2821  *
2822  * \param pvt DAHDI private structure
2823  * \param caller Caller-id information to set.
2824  *
2825  * \return Nothing
2826  */
2827 static void my_set_callerid(void *pvt, const struct ast_party_caller *caller)
2828 {
2829         struct dahdi_pvt *p = pvt;
2830
2831         ast_copy_string(p->cid_num,
2832                 S_COR(caller->id.number.valid, caller->id.number.str, ""),
2833                 sizeof(p->cid_num));
2834         ast_copy_string(p->cid_name,
2835                 S_COR(caller->id.name.valid, caller->id.name.str, ""),
2836                 sizeof(p->cid_name));
2837         ast_copy_string(p->cid_subaddr,
2838                 S_COR(caller->id.subaddress.valid, caller->id.subaddress.str, ""),
2839                 sizeof(p->cid_subaddr));
2840         p->cid_ton = caller->id.number.plan;
2841         p->callingpres = ast_party_id_presentation(&caller->id);
2842         if (caller->id.tag) {
2843                 ast_copy_string(p->cid_tag, caller->id.tag, sizeof(p->cid_tag));
2844         }
2845         ast_copy_string(p->cid_ani,
2846                 S_COR(caller->ani.number.valid, caller->ani.number.str, ""),
2847                 sizeof(p->cid_ani));
2848         p->cid_ani2 = caller->ani2;
2849 }
2850 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
2851
2852 #if defined(HAVE_PRI) || defined(HAVE_SS7)
2853 /*!
2854  * \internal
2855  * \brief Set the Dialed Number Identifier.
2856  * \since 1.8
2857  *
2858  * \param pvt DAHDI private structure
2859  * \param dnid Dialed Number Identifier string.
2860  *
2861  * \return Nothing
2862  */
2863 static void my_set_dnid(void *pvt, const char *dnid)
2864 {
2865         struct dahdi_pvt *p = pvt;
2866
2867         ast_copy_string(p->dnid, dnid, sizeof(p->dnid));
2868 }
2869 #endif  /* defined(HAVE_PRI) || defined(HAVE_SS7) */
2870
2871 #if defined(HAVE_PRI)
2872 /*!
2873  * \internal
2874  * \brief Set the Redirecting Directory Number Information Service (RDNIS).
2875  * \since 1.8
2876  *
2877  * \param pvt DAHDI private structure
2878  * \param rdnis Redirecting Directory Number Information Service (RDNIS) string.
2879  *
2880  * \return Nothing
2881  */
2882 static void my_set_rdnis(void *pvt, const char *rdnis)
2883 {
2884         struct dahdi_pvt *p = pvt;
2885
2886         ast_copy_string(p->rdnis, rdnis, sizeof(p->rdnis));
2887 }
2888 #endif  /* defined(HAVE_PRI) */
2889
2890 #if defined(HAVE_PRI)
2891 /*!
2892  * \internal
2893  * \brief Make a dialstring for native ISDN CC to recall properly.
2894  * \since 1.8
2895  *
2896  * \param priv Channel private control structure.
2897  * \param buf Where to put the modified dialstring.
2898  * \param buf_size Size of modified dialstring buffer.
2899  *
2900  * \details
2901  * original dialstring:
2902  * DAHDI/[i<span>-](g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
2903  *
2904  * The modified dialstring will have prefixed the channel-group section
2905  * with the ISDN channel restriction.
2906  *
2907  * buf:
2908  * DAHDI/i<span>-(g|G|r|R)<group#(0-63)>[c|r<cadance#>|d][/extension[/options]]
2909  *
2910  * The routine will check to see if the ISDN channel restriction is already
2911  * in the original dialstring.
2912  *
2913  * \return Nothing
2914  */
2915 static void my_pri_make_cc_dialstring(void *priv, char *buf, size_t buf_size)
2916 {
2917         char *dial;
2918         struct dahdi_pvt *pvt;
2919         AST_DECLARE_APP_ARGS(args,
2920                 AST_APP_ARG(tech);      /* channel technology token */
2921                 AST_APP_ARG(group);     /* channel/group token */
2922                 //AST_APP_ARG(ext);     /* extension token */
2923                 //AST_APP_ARG(opts);    /* options token */
2924                 //AST_APP_ARG(other);   /* Any remining unused arguments */
2925         );
2926
2927         pvt = priv;
2928         dial = ast_strdupa(pvt->dialstring);
2929         AST_NONSTANDARD_APP_ARGS(args, dial, '/');
2930         if (!args.tech) {
2931                 ast_copy_string(buf, pvt->dialstring, buf_size);
2932                 return;
2933         }
2934         if (!args.group) {
2935                 /* Append the ISDN span channel restriction to the dialstring. */
2936                 snprintf(buf, buf_size, "%s/i%d-", args.tech, pvt->pri->span);
2937                 return;
2938         }
2939         if (isdigit(args.group[0]) || args.group[0] == 'i' || strchr(args.group, '!')) {
2940                 /* The ISDN span channel restriction is not needed or already
2941                  * in the dialstring. */
2942                 ast_copy_string(buf, pvt->dialstring, buf_size);
2943                 return;
2944         }
2945         /* Insert the ISDN span channel restriction into the dialstring. */
2946         snprintf(buf, buf_size, "%s/i%d-%s", args.tech, pvt->pri->span, args.group);
2947 }
2948 #endif  /* defined(HAVE_PRI) */
2949
2950 #if defined(HAVE_PRI)
2951 /*!
2952  * \internal
2953  * \brief Reevaluate the PRI span device state.
2954  * \since 1.8
2955  *
2956  * \param pri Asterisk D channel control structure.
2957  *
2958  * \return Nothing
2959  *
2960  * \note Assumes the pri->lock is already obtained.
2961  */
2962 static void dahdi_pri_update_span_devstate(struct sig_pri_span *pri)
2963 {
2964         unsigned idx;
2965         unsigned num_b_chans;   /* Number of B channels provisioned on the span. */
2966         unsigned in_use;                /* Number of B channels in use on the span. */
2967         unsigned in_alarm;              /* TRUE if the span is in alarm condition. */
2968         enum ast_device_state new_state;
2969
2970         /* Count the number of B channels and the number of B channels in use. */
2971         num_b_chans = 0;
2972         in_use = 0;
2973         in_alarm = 1;
2974         for (idx = pri->numchans; idx--;) {
2975                 if (pri->pvts[idx] && !pri->pvts[idx]->no_b_channel) {
2976                         /* This is a B channel interface. */
2977                         ++num_b_chans;
2978                         if (!sig_pri_is_chan_available(pri->pvts[idx])) {
2979                                 ++in_use;
2980                         }
2981                         if (!pri->pvts[idx]->inalarm) {
2982                                 /* There is a channel that is not in alarm. */
2983                                 in_alarm = 0;
2984                         }
2985                 }
2986         }
2987
2988         /* Update the span congestion device state and report any change. */
2989         if (in_alarm) {
2990                 new_state = AST_DEVICE_UNAVAILABLE;
2991         } else {
2992                 new_state = num_b_chans == in_use ? AST_DEVICE_BUSY : AST_DEVICE_NOT_INUSE;
2993         }
2994         if (pri->congestion_devstate != new_state) {
2995                 pri->congestion_devstate = new_state;
2996                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_NOT_CACHABLE, "DAHDI/I%d/congestion", pri->span);
2997         }
2998 #if defined(THRESHOLD_DEVSTATE_PLACEHOLDER)
2999         /* Update the span threshold device state and report any change. */
3000         if (in_alarm) {
3001                 new_state = AST_DEVICE_UNAVAILABLE;
3002         } else if (!in_use) {
3003                 new_state = AST_DEVICE_NOT_INUSE;
3004         } else if (!pri->user_busy_threshold) {
3005                 new_state = in_use < num_b_chans ? AST_DEVICE_INUSE : AST_DEVICE_BUSY;
3006         } else {
3007                 new_state = in_use < pri->user_busy_threshold ? AST_DEVICE_INUSE
3008                         : AST_DEVICE_BUSY;
3009         }
3010         if (pri->threshold_devstate != new_state) {
3011                 pri->threshold_devstate = new_state;
3012                 ast_devstate_changed(AST_DEVICE_UNKNOWN, AST_DEVSTATE_NOT_CACHABLE, "DAHDI/I%d/threshold", pri->span);
3013         }
3014 #endif  /* defined(THRESHOLD_DEVSTATE_PLACEHOLDER) */
3015 }
3016 #endif  /* defined(HAVE_PRI) */
3017
3018 #if defined(HAVE_PRI)
3019 /*!
3020  * \internal
3021  * \brief Reference this module.
3022  * \since 1.8
3023  *
3024  * \return Nothing
3025  */
3026 static void my_module_ref(void)
3027 {
3028         ast_module_ref(ast_module_info->self);
3029 }
3030 #endif  /* defined(HAVE_PRI) */
3031
3032 #if defined(HAVE_PRI)
3033 /*!
3034  * \internal
3035  * \brief Unreference this module.
3036  * \since 1.8
3037  *
3038  * \return Nothing
3039  */
3040 static void my_module_unref(void)
3041 {
3042         ast_module_unref(ast_module_info->self);
3043 }
3044 #endif  /* defined(HAVE_PRI) */
3045
3046 #if defined(HAVE_PRI)
3047 #if defined(HAVE_PRI_CALL_WAITING)
3048 static void my_pri_init_config(void *priv, struct sig_pri_span *pri);
3049 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
3050 static int dahdi_new_pri_nobch_channel(struct sig_pri_span *pri);
3051
3052 struct sig_pri_callback sig_pri_callbacks =
3053 {
3054         .handle_dchan_exception = my_handle_dchan_exception,
3055         .play_tone = my_pri_play_tone,
3056         .set_echocanceller = my_set_echocanceller,
3057         .dsp_reset_and_flush_digits = my_dsp_reset_and_flush_digits,
3058         .lock_private = my_lock_private,
3059         .unlock_private = my_unlock_private,
3060         .deadlock_avoidance_private = my_deadlock_avoidance_private,
3061         .new_ast_channel = my_new_pri_ast_channel,
3062         .fixup_chans = my_pri_fixup_chans,
3063         .set_alarm = my_set_alarm,
3064         .set_dialing = my_set_dialing,
3065         .set_outgoing = my_set_outgoing,
3066         .set_digital = my_set_digital,
3067         .set_callerid = my_set_callerid,
3068         .set_dnid = my_set_dnid,
3069         .set_rdnis = my_set_rdnis,
3070         .new_nobch_intf = dahdi_new_pri_nobch_channel,
3071 #if defined(HAVE_PRI_CALL_WAITING)
3072         .init_config = my_pri_init_config,
3073 #endif  /* defined(HAVE_PRI_CALL_WAITING) */
3074         .get_orig_dialstring = my_get_orig_dialstring,
3075         .make_cc_dialstring = my_pri_make_cc_dialstring,
3076         .update_span_devstate = dahdi_pri_update_span_devstate,
3077         .module_ref = my_module_ref,
3078         .module_unref = my_module_unref,
3079         .dial_digits = my_pri_dial_digits,
3080         .open_media = my_pri_ss7_open_media,
3081         .ami_channel_event = my_ami_channel_event,
3082         .destroy_later = pri_queue_for_destruction,
3083 };
3084 #endif  /* defined(HAVE_PRI) */
3085
3086 #if defined(HAVE_SS7)
3087 /*!
3088  * \internal
3089  * \brief Handle the SS7 link exception.
3090  * \since 1.8
3091  *
3092  * \param linkset Controlling linkset for the channel.
3093  * \param which Link index of the signaling channel.
3094  *
3095  * \return Nothing
3096  */
3097 static void my_handle_link_exception(struct sig_ss7_linkset *linkset, int which)
3098 {
3099         int event;
3100
3101         if (ioctl(linkset->fds[which], DAHDI_GETEVENT, &event)) {
3102                 ast_log(LOG_ERROR, "SS7: Error in exception retrieval on span %d/%d!\n",
3103                         linkset->span, which);
3104                 return;
3105         }
3106         switch (event) {
3107         case DAHDI_EVENT_NONE:
3108                 break;
3109         case DAHDI_EVENT_ALARM:
3110                 ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
3111                         event2str(event), event, linkset->span, which);
3112                 sig_ss7_link_alarm(linkset, which);
3113                 break;
3114         case DAHDI_EVENT_NOALARM:
3115                 ast_log(LOG_ERROR, "SS7 got event: %s(%d) on span %d/%d\n",
3116                         event2str(event), event, linkset->span, which);
3117                 sig_ss7_link_noalarm(linkset, which);
3118                 break;
3119         default:
3120                 ast_log(LOG_NOTICE, "SS7 got event: %s(%d) on span %d/%d\n",
3121                         event2str(event), event, linkset->span, which);
3122                 break;
3123         }
3124 }
3125 #endif  /* defined(HAVE_SS7) */
3126
3127 #if defined(HAVE_SS7)
3128 static void my_ss7_set_loopback(void *pvt, int enable)
3129 {
3130         struct dahdi_pvt *p = pvt;
3131
3132         if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_LOOPBACK, &enable)) {
3133                 ast_log(LOG_WARNING, "Unable to set loopback on channel %d: %s\n", p->channel,
3134                         strerror(errno));
3135         }
3136 }
3137 #endif  /* defined(HAVE_SS7) */
3138
3139 #if defined(HAVE_SS7)
3140 /*!
3141  * \internal
3142  * \brief Find the linkset to which SS7 belongs.
3143  * \since 11.0
3144  *
3145  * \param ss7 structure to match on.
3146  *
3147  * \retval linkset if found.
3148  * \retval NULL if not found.
3149  */
3150 static struct sig_ss7_linkset *my_ss7_find_linkset(struct ss7 *ss7)
3151 {
3152         int idx;
3153
3154         if (!ss7) {
3155                 return NULL;
3156         }
3157
3158         for (idx = 0; idx < NUM_SPANS; ++idx) {
3159                 if (linksets[idx].ss7.ss7 == ss7) {
3160                         return &linksets[idx].ss7;
3161                 }
3162         }
3163         return NULL;
3164 }
3165 #endif  /* defined(HAVE_SS7) */
3166
3167 #if defined(HAVE_SS7)
3168 /*!
3169  * \internal
3170  * \brief Create a new asterisk channel structure for SS7.
3171  * \since 1.8
3172  *
3173  * \param pvt Private channel structure.
3174  * \param state Initial state of new channel.
3175  * \param law Combanding law to use.
3176  * \param exten Dialplan extension for incoming call.
3177  * \param requestor Channel requesting this new channel.
3178  *
3179  * \retval ast_channel on success.
3180  * \retval NULL on error.
3181  */
3182 static struct ast_channel *my_new_ss7_ast_channel(void *pvt, int state, enum sig_ss7_law law, char *exten, const struct ast_assigned_ids *assignedids, const struct ast_channel *requestor)
3183 {
3184         struct dahdi_pvt *p = pvt;
3185         int audio;
3186         int newlaw;
3187         struct ast_callid *callid = NULL;
3188         int callid_created = ast_callid_threadstorage_auto(&callid);
3189
3190         /* Set to audio mode at this point */
3191         audio = 1;
3192         if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &audio) == -1)
3193                 ast_log(LOG_WARNING, "Unable to set audio mode on channel %d to %d: %s\n",
3194                         p->channel, audio, strerror(errno));
3195
3196         if (law != SIG_SS7_DEFLAW) {
3197                 dahdi_setlaw(p->subs[SUB_REAL].dfd,
3198                         (law == SIG_SS7_ULAW) ? DAHDI_LAW_MULAW : DAHDI_LAW_ALAW);
3199         }
3200
3201         ast_copy_string(p->exten, exten, sizeof(p->exten));
3202
3203         newlaw = -1;
3204         switch (law) {
3205         case SIG_SS7_DEFLAW:
3206                 newlaw = 0;
3207                 break;
3208         case SIG_SS7_ALAW:
3209                 newlaw = DAHDI_LAW_ALAW;
3210                 break;
3211         case SIG_SS7_ULAW:
3212                 newlaw = DAHDI_LAW_MULAW;
3213                 break;
3214         }
3215         return dahdi_new_callid_clean(p, state, 0, SUB_REAL, newlaw, assignedids, requestor, callid, callid_created);
3216 }
3217 #endif  /* defined(HAVE_SS7) */
3218
3219 #if defined(HAVE_SS7)
3220 static int sig_ss7_tone_to_dahditone(enum sig_ss7_tone tone)
3221 {
3222         switch (tone) {
3223         case SIG_SS7_TONE_RINGTONE:
3224                 return DAHDI_TONE_RINGTONE;
3225         case SIG_SS7_TONE_STUTTER:
3226                 return DAHDI_TONE_STUTTER;
3227         case SIG_SS7_TONE_CONGESTION:
3228                 return DAHDI_TONE_CONGESTION;
3229         case SIG_SS7_TONE_DIALTONE:
3230                 return DAHDI_TONE_DIALTONE;
3231         case SIG_SS7_TONE_DIALRECALL: