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