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