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