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