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