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