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