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