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