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