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