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