2 * Asterisk -- An open source telephony toolkit.
4 * Copyright (C) 1999 - 2006, Digium, Inc.
6 * Mark Spencer <markster@digium.com>
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.
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.
21 * \brief DAHDI for Pseudo TDM
23 * \author Mark Spencer <markster@digium.com>
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.
29 * You need to install libraries before you attempt to compile
30 * and install the DAHDI channel.
33 * \arg \ref Config_dahdi
35 * \ingroup channel_drivers
37 * \todo Deprecate the "musiconhold" configuration option post 1.4
41 <depend>res_smdi</depend>
42 <depend>dahdi</depend>
43 <depend>tonezone</depend>
51 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
57 #include <sys/signal.h>
59 #include <sys/ioctl.h>
63 #include <dahdi/user.h>
64 #include <dahdi/tonezone.h>
78 #include "asterisk/lock.h"
79 #include "asterisk/channel.h"
80 #include "asterisk/config.h"
81 #include "asterisk/module.h"
82 #include "asterisk/pbx.h"
83 #include "asterisk/file.h"
84 #include "asterisk/ulaw.h"
85 #include "asterisk/alaw.h"
86 #include "asterisk/callerid.h"
87 #include "asterisk/adsi.h"
88 #include "asterisk/cli.h"
89 #include "asterisk/cdr.h"
90 #include "asterisk/features.h"
91 #include "asterisk/musiconhold.h"
92 #include "asterisk/say.h"
93 #include "asterisk/tdd.h"
94 #include "asterisk/app.h"
95 #include "asterisk/dsp.h"
96 #include "asterisk/astdb.h"
97 #include "asterisk/manager.h"
98 #include "asterisk/causes.h"
99 #include "asterisk/term.h"
100 #include "asterisk/utils.h"
101 #include "asterisk/transcap.h"
102 #include "asterisk/stringfields.h"
103 #include "asterisk/abstract_jb.h"
104 #include "asterisk/smdi.h"
105 #include "asterisk/astobj.h"
106 #include "asterisk/event.h"
107 #include "asterisk/devicestate.h"
108 #include "asterisk/paths.h"
111 <application name="DAHDISendKeypadFacility" language="en_US">
113 Send digits out of band over a PRI.
116 <parameter name="digits" required="true" />
119 <para>This application will send the given string of digits in a Keypad
120 Facility IE over the current channel.</para>
123 <application name="DAHDISendCallreroutingFacility" language="en_US">
125 Send QSIG call rerouting facility over a PRI.
128 <parameter name="destination" required="true">
129 <para>Destination number.</para>
131 <parameter name="original">
132 <para>Original called number.</para>
134 <parameter name="reason">
135 <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
139 <para>This application will send a Callrerouting Facility IE over the
140 current channel.</para>
143 <application name="DAHDIAcceptR2Call" language="en_US">
145 Accept an R2 call if its not already accepted (you still need to answer it)
148 <parameter name="charge" required="true">
149 <para>Yes or No.</para>
150 <para>Whether you want to accept the call with charge or without charge.</para>
154 <para>This application will Accept the R2 call either with charge or no charge.</para>
159 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
161 static const char *lbostr[] = {
162 "0 db (CSU)/0-133 feet (DSX-1)",
163 "133-266 feet (DSX-1)",
164 "266-399 feet (DSX-1)",
165 "399-533 feet (DSX-1)",
166 "533-655 feet (DSX-1)",
172 /*! Global jitterbuffer configuration - by default, jb is disabled */
173 static struct ast_jb_conf default_jbconf =
177 .resync_threshold = -1,
180 static struct ast_jb_conf global_jbconf;
182 /* define this to send PRI user-user information elements */
183 #undef SUPPORT_USERUSER
186 * \note Define ZHONE_HACK to cause us to go off hook and then back on hook when
187 * the user hangs up to reset the state machine so ring works properly.
188 * This is used to be able to support kewlstart by putting the zhone in
189 * groundstart mode since their forward disconnect supervision is entirely
190 * broken even though their documentation says it isn't and their support
191 * is entirely unwilling to provide any assistance with their channel banks
192 * even though their web site says they support their products for life.
194 /* #define ZHONE_HACK */
197 * Define if you want to check the hook state for an FXO (FXS signalled) interface
198 * before dialing on it. Certain FXO interfaces always think they're out of
199 * service with this method however.
201 /* #define DAHDI_CHECK_HOOKSTATE */
203 /*! \brief Typically, how many rings before we should send Caller*ID */
204 #define DEFAULT_CIDRINGS 1
206 #define CHANNEL_PSEUDO -12
208 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
211 /*! \brief Signaling types that need to use MF detection should be placed in this macro */
212 #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))
214 static const char tdesc[] = "DAHDI Telephony Driver"
215 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
229 #if defined(HAVE_PRI) || defined(HAVE_SS7)
237 static const char config[] = "chan_dahdi.conf";
239 #define SIG_EM DAHDI_SIG_EM
240 #define SIG_EMWINK (0x0100000 | DAHDI_SIG_EM)
241 #define SIG_FEATD (0x0200000 | DAHDI_SIG_EM)
242 #define SIG_FEATDMF (0x0400000 | DAHDI_SIG_EM)
243 #define SIG_FEATB (0x0800000 | DAHDI_SIG_EM)
244 #define SIG_E911 (0x1000000 | DAHDI_SIG_EM)
245 #define SIG_FEATDMF_TA (0x2000000 | DAHDI_SIG_EM)
246 #define SIG_FGC_CAMA (0x4000000 | DAHDI_SIG_EM)
247 #define SIG_FGC_CAMAMF (0x8000000 | DAHDI_SIG_EM)
248 #define SIG_FXSLS DAHDI_SIG_FXSLS
249 #define SIG_FXSGS DAHDI_SIG_FXSGS
250 #define SIG_FXSKS DAHDI_SIG_FXSKS
251 #define SIG_FXOLS DAHDI_SIG_FXOLS
252 #define SIG_FXOGS DAHDI_SIG_FXOGS
253 #define SIG_FXOKS DAHDI_SIG_FXOKS
254 #define SIG_PRI DAHDI_SIG_CLEAR
255 #define SIG_BRI (0x2000000 | DAHDI_SIG_CLEAR)
256 #define SIG_BRI_PTMP (0X4000000 | DAHDI_SIG_CLEAR)
257 #define SIG_SS7 (0x1000000 | DAHDI_SIG_CLEAR)
258 #define SIG_MFCR2 DAHDI_SIG_CAS
259 #define SIG_SF DAHDI_SIG_SF
260 #define SIG_SFWINK (0x0100000 | DAHDI_SIG_SF)
261 #define SIG_SF_FEATD (0x0200000 | DAHDI_SIG_SF)
262 #define SIG_SF_FEATDMF (0x0400000 | DAHDI_SIG_SF)
263 #define SIG_SF_FEATB (0x0800000 | DAHDI_SIG_SF)
264 #define SIG_EM_E1 DAHDI_SIG_EM_E1
265 #define SIG_GR303FXOKS (0x0100000 | DAHDI_SIG_FXOKS)
266 #define SIG_GR303FXSKS (0x0100000 | DAHDI_SIG_FXSKS)
269 #define NUM_SPANS DAHDI_MAX_SPANS
273 #define NUM_DCHANS 4 /*!< No more than 4 d-channels */
274 #define MAX_CHANNELS 672 /*!< No more than a DS3 per trunk group */
276 #define CHAN_PSEUDO -2
278 #define DCHAN_PROVISIONED (1 << 0)
279 #define DCHAN_NOTINALARM (1 << 1)
280 #define DCHAN_UP (1 << 2)
282 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
284 /* Overlap dialing option types */
285 #define DAHDI_OVERLAPDIAL_NONE 0
286 #define DAHDI_OVERLAPDIAL_OUTGOING 1
287 #define DAHDI_OVERLAPDIAL_INCOMING 2
288 #define DAHDI_OVERLAPDIAL_BOTH (DAHDI_OVERLAPDIAL_INCOMING|DAHDI_OVERLAPDIAL_OUTGOING)
290 #define CALLPROGRESS_PROGRESS 1
291 #define CALLPROGRESS_FAX_OUTGOING 2
292 #define CALLPROGRESS_FAX_INCOMING 4
293 #define CALLPROGRESS_FAX (CALLPROGRESS_FAX_INCOMING | CALLPROGRESS_FAX_OUTGOING)
295 static char defaultcic[64] = "";
296 static char defaultozz[64] = "";
298 static char parkinglot[AST_MAX_EXTENSION] = ""; /*!< Default parking lot for this channel */
300 /*! Run this script when the MWI state changes on an FXO line, if mwimonitor is enabled */
301 static char mwimonitornotify[PATH_MAX] = "";
302 #ifndef HAVE_DAHDI_LINEREVERSE_VMWI
303 static int mwisend_rpas = 0;
306 static char progzone[10] = "";
308 static int usedistinctiveringdetection = 0;
309 static int distinctiveringaftercid = 0;
311 static int numbufs = 4;
313 static int mwilevel = 512;
316 static struct ast_channel inuse;
317 #ifdef PRI_GETSET_TIMERS
318 static int pritimers[PRI_MAX_TIMERS];
320 static int pridebugfd = -1;
321 static char pridebugfilename[1024] = "";
324 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
325 static int firstdigittimeout = 16000;
327 /*! \brief How long to wait for following digits (FXO logic) */
328 static int gendigittimeout = 8000;
330 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
331 static int matchdigittimeout = 3000;
333 /*! \brief Protect the interface list (of dahdi_pvt's) */
334 AST_MUTEX_DEFINE_STATIC(iflock);
336 /* QSIG channel mapping option types */
337 #define DAHDI_CHAN_MAPPING_PHYSICAL 0
338 #define DAHDI_CHAN_MAPPING_LOGICAL 1
341 static int ifcount = 0;
344 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
347 /*! \brief Protect the monitoring thread, so only one process can kill or start it, and not
348 when it's doing something critical. */
349 AST_MUTEX_DEFINE_STATIC(monlock);
351 /*! \brief This is the thread for the monitor which checks for input on the channels
352 which are not currently in use. */
353 static pthread_t monitor_thread = AST_PTHREADT_NULL;
354 static ast_cond_t ss_thread_complete;
355 AST_MUTEX_DEFINE_STATIC(ss_thread_lock);
356 AST_MUTEX_DEFINE_STATIC(restart_lock);
357 static int ss_thread_count = 0;
358 static int num_restart_pending = 0;
360 static int restart_monitor(void);
362 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);
364 static int dahdi_sendtext(struct ast_channel *c, const char *text);
366 static void mwi_event_cb(const struct ast_event *event, void *userdata)
368 /* This module does not handle MWI in an event-based manner. However, it
369 * subscribes to MWI for each mailbox that is configured so that the core
370 * knows that we care about it. Then, chan_dahdi will get the MWI from the
371 * event cache instead of checking the mailbox directly. */
374 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
375 static inline int dahdi_get_event(int fd)
378 if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
383 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
384 static inline int dahdi_wait_event(int fd)
387 i = DAHDI_IOMUX_SIGEVENT;
388 if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
390 if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
395 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
396 #define READ_SIZE 160
398 #define MASK_AVAIL (1 << 0) /*!< Channel available for PRI use */
399 #define MASK_INUSE (1 << 1) /*!< Channel currently in use */
401 #define CALLWAITING_SILENT_SAMPLES ( (300 * 8) / READ_SIZE) /*!< 300 ms */
402 #define CALLWAITING_REPEAT_SAMPLES ( (10000 * 8) / READ_SIZE) /*!< 10,000 ms */
403 #define CIDCW_EXPIRE_SAMPLES ( (500 * 8) / READ_SIZE) /*!< 500 ms */
404 #define MIN_MS_SINCE_FLASH ( (2000) ) /*!< 2000 ms */
405 #define DEFAULT_RINGT ( (8000 * 8) / READ_SIZE) /*!< 8,000 ms */
410 * \brief Configured ring timeout base.
411 * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
413 static int ringt_base = DEFAULT_RINGT;
417 #define LINKSTATE_INALARM (1 << 0)
418 #define LINKSTATE_STARTING (1 << 1)
419 #define LINKSTATE_UP (1 << 2)
420 #define LINKSTATE_DOWN (1 << 3)
422 #define SS7_NAI_DYNAMIC -1
424 #define LINKSET_FLAG_EXPLICITACM (1 << 0)
427 pthread_t master; /*!< Thread of master */
431 int linkstate[NUM_DCHANS];
435 LINKSET_STATE_DOWN = 0,
438 char called_nai; /*!< Called Nature of Address Indicator */
439 char calling_nai; /*!< Calling Nature of Address Indicator */
440 char internationalprefix[10]; /*!< country access code ('00' for european dialplans) */
441 char nationalprefix[10]; /*!< area access code ('0' for european dialplans) */
442 char subscriberprefix[20]; /*!< area access code + area code ('0'+area code for european dialplans) */
443 char unknownprefix[20]; /*!< for unknown dialplans */
445 struct dahdi_pvt *pvts[MAX_CHANNELS]; /*!< Member channel pvt structs */
446 int flags; /*!< Linkset flags */
449 static struct dahdi_ss7 linksets[NUM_SPANS];
451 static int cur_ss7type = -1;
452 static int cur_linkset = -1;
453 static int cur_pointcode = -1;
454 static int cur_cicbeginswith = -1;
455 static int cur_adjpointcode = -1;
456 static int cur_networkindicator = -1;
457 static int cur_defaultdpc = -1;
458 #endif /* HAVE_SS7 */
462 pthread_t r2master; /*!< Thread of master */
463 openr2_context_t *protocol_context; /*!< OpenR2 context handle */
464 struct dahdi_pvt *pvts[MAX_CHANNELS]; /*!< Member channel pvt structs */
465 int numchans; /*!< Number of channels in this R2 block */
466 int monitored_count; /*!< Number of channels being monitored */
467 ast_mutex_t monitored_count_lock; /*!< lock access to the counter */
468 ast_cond_t do_monitor; /*!< Condition to wake up the monitor thread when there's work to do */
471 struct dahdi_mfcr2_conf {
472 openr2_variant_t variant;
474 int metering_pulse_timeout;
479 int allow_collect_calls:1;
481 int accept_on_offer:1;
482 int forced_release:1;
484 int immediate_accept:1;
485 char logdir[OR2_MAX_PATH];
486 char r2proto_file[OR2_MAX_PATH];
487 openr2_log_level_t loglevel;
488 openr2_calling_party_category_t category;
491 /* malloc'd array of malloc'd r2links */
492 static struct dahdi_mfcr2 **r2links;
493 /* how many r2links have been malloc'd */
494 static int r2links_count = 0;
496 #endif /* HAVE_OPENR2 */
500 #define PVT_TO_CHANNEL(p) (((p)->prioffset) | ((p)->logicalspan << 8) | (p->pri->mastertrunkgroup ? 0x10000 : 0))
501 #define PRI_CHANNEL(p) ((p) & 0xff)
502 #define PRI_SPAN(p) (((p) >> 8) & 0xff)
503 #define PRI_EXPLICIT(p) (((p) >> 16) & 0x01)
506 pthread_t master; /*!< Thread of master */
507 ast_mutex_t lock; /*!< Mutex */
508 char idleext[AST_MAX_EXTENSION]; /*!< Where to idle extra calls */
509 char idlecontext[AST_MAX_CONTEXT]; /*!< What context to use for idle */
510 char idledial[AST_MAX_EXTENSION]; /*!< What to dial before dumping */
511 int minunused; /*!< Min # of channels to keep empty */
512 int minidle; /*!< Min # of "idling" calls to keep active */
513 int nodetype; /*!< Node type */
514 int switchtype; /*!< Type of switch to emulate */
515 int nsf; /*!< Network-Specific Facilities */
516 int dialplan; /*!< Dialing plan */
517 int localdialplan; /*!< Local dialing plan */
518 char internationalprefix[10]; /*!< country access code ('00' for european dialplans) */
519 char nationalprefix[10]; /*!< area access code ('0' for european dialplans) */
520 char localprefix[20]; /*!< area access code + area code ('0'+area code for european dialplans) */
521 char privateprefix[20]; /*!< for private dialplans */
522 char unknownprefix[20]; /*!< for unknown dialplans */
523 int dchannels[NUM_DCHANS]; /*!< What channel are the dchannels on */
524 int trunkgroup; /*!< What our trunkgroup is */
525 int mastertrunkgroup; /*!< What trunk group is our master */
526 int prilogicalspan; /*!< Logical span number within trunk group */
527 int numchans; /*!< Num of channels we represent */
528 int overlapdial; /*!< In overlap dialing mode */
529 int qsigchannelmapping; /*!< QSIG channel mapping type */
530 int discardremoteholdretrieval; /*!< shall remote hold or remote retrieval notifications be discarded? */
531 int facilityenable; /*!< Enable facility IEs */
532 struct pri *dchans[NUM_DCHANS]; /*!< Actual d-channels */
533 int dchanavail[NUM_DCHANS]; /*!< Whether each channel is available */
534 struct pri *pri; /*!< Currently active D-channel */
535 /*! \brief TRUE if to dump PRI event info (Tested but never set) */
537 int fds[NUM_DCHANS]; /*!< FD's for d-channels */
538 /*! \brief Value set but not used */
540 /*! \brief Span number put into user output messages */
542 /*! \brief TRUE if span is being reset/restarted */
544 /*! \brief Current position during a reset (-1 if not started) */
546 #ifdef HAVE_PRI_INBANDDISCONNECT
547 unsigned int inbanddisconnect:1; /*!< Should we support inband audio after receiving DISCONNECT? */
549 time_t lastreset; /*!< time when unused channels were last reset */
550 long resetinterval; /*!< Interval (in seconds) for resetting unused channels */
551 /*! \brief ISDN signalling type (SIG_PRI, SIG_BRI, SIG_BRI_PTMP, etc...) */
553 struct dahdi_pvt *pvts[MAX_CHANNELS]; /*!< Member channel pvt structs */
554 struct dahdi_pvt *crvs; /*!< Member CRV structs */
555 struct dahdi_pvt *crvend; /*!< Pointer to end of CRV structs */
559 static struct dahdi_pri pris[NUM_SPANS];
562 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
564 #define DEFAULT_PRI_DEBUG 0
567 static inline void pri_rel(struct dahdi_pri *pri)
569 ast_mutex_unlock(&pri->lock);
573 /*! Shut up the compiler */
577 #define SUB_REAL 0 /*!< Active call */
578 #define SUB_CALLWAIT 1 /*!< Call-Waiting call on hold */
579 #define SUB_THREEWAY 2 /*!< Three-way call */
581 /* Polarity states */
582 #define POLARITY_IDLE 0
583 #define POLARITY_REV 1
586 struct distRingData {
590 struct ringContextData {
591 char contextData[AST_MAX_CONTEXT];
593 struct dahdi_distRings {
594 struct distRingData ringnum[3];
595 struct ringContextData ringContext[3];
598 static char *subnames[] = {
604 struct dahdi_subchannel {
606 struct ast_channel *owner;
608 short buffer[AST_FRIENDLY_OFFSET/2 + READ_SIZE];
609 struct ast_frame f; /*!< One frame for each channel. How did this ever work before? */
610 unsigned int needringing:1;
611 unsigned int needbusy:1;
612 unsigned int needcongestion:1;
613 unsigned int needcallerid:1;
614 unsigned int needanswer:1;
615 unsigned int needflash:1;
616 unsigned int needhold:1;
617 unsigned int needunhold:1;
618 unsigned int linear:1;
619 unsigned int inthreeway:1;
620 struct dahdi_confinfo curconf;
623 #define CONF_USER_REAL (1 << 0)
624 #define CONF_USER_THIRDCALL (1 << 1)
628 /* States for sending MWI message
629 * First three states are required for send Ring Pulse Alert Signal
641 struct mwisend_info {
642 struct timeval pause;
643 mwisend_states mwisend_current;
646 static struct dahdi_pvt {
648 struct ast_channel *owner; /*!< Our current active owner (if applicable) */
649 /*!< Up to three channels can be associated with this call */
651 struct dahdi_subchannel sub_unused; /*!< Just a safety precaution */
652 struct dahdi_subchannel subs[3]; /*!< Sub-channels */
653 struct dahdi_confinfo saveconf; /*!< Saved conference info */
655 struct dahdi_pvt *slaves[MAX_SLAVES]; /*!< Slave to us (follows our conferencing) */
656 struct dahdi_pvt *master; /*!< Master to us (we follow their conferencing) */
657 int inconference; /*!< If our real should be in the conference */
659 int bufsize; /*!< Size of the buffers */
660 int buf_no; /*!< Number of buffers */
661 int buf_policy; /*!< Buffer policy */
662 int faxbuf_no; /*!< Number of Fax buffers */
663 int faxbuf_policy; /*!< Fax buffer policy */
664 int sig; /*!< Signalling style */
666 * \brief Nonzero if the signaling type is sent over a radio.
667 * \note Set to a couple of nonzero values but it is only tested like a boolean.
670 int outsigmod; /*!< Outbound Signalling style (modifier) */
671 int oprmode; /*!< "Operator Services" mode */
672 struct dahdi_pvt *oprpeer; /*!< "Operator Services" peer tech_pvt ptr */
673 /*! \brief Amount of gain to increase during caller id */
675 /*! \brief Rx gain set by chan_dahdi.conf */
677 /*! \brief Tx gain set by chan_dahdi.conf */
679 int tonezone; /*!< tone zone for this chan, or -1 for default */
680 struct dahdi_pvt *next; /*!< Next channel in list */
681 struct dahdi_pvt *prev; /*!< Prev channel in list */
686 * \brief TRUE if ADSI (Analog Display Services Interface) available
687 * \note Set from the "adsi" value read in from chan_dahdi.conf
691 * \brief TRUE if we can use a polarity reversal to mark when an outgoing
692 * call is answered by the remote party.
693 * \note Set from the "answeronpolarityswitch" value read in from chan_dahdi.conf
695 unsigned int answeronpolarityswitch:1;
697 * \brief TRUE if busy detection is enabled.
698 * (Listens for the beep-beep busy pattern.)
699 * \note Set from the "busydetect" value read in from chan_dahdi.conf
701 unsigned int busydetect:1;
703 * \brief TRUE if call return is enabled.
704 * (*69, if your dialplan doesn't catch this first)
705 * \note Set from the "callreturn" value read in from chan_dahdi.conf
707 unsigned int callreturn:1;
709 * \brief TRUE if busy extensions will hear the call-waiting tone
710 * and can use hook-flash to switch between callers.
711 * \note Can be disabled by dialing *70.
712 * \note Initialized with the "callwaiting" value read in from chan_dahdi.conf
714 unsigned int callwaiting:1;
716 * \brief TRUE if send caller ID for Call Waiting
717 * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
719 unsigned int callwaitingcallerid:1;
721 * \brief TRUE if support for call forwarding enabled.
722 * Dial *72 to enable call forwarding.
723 * Dial *73 to disable call forwarding.
724 * \note Set from the "cancallforward" value read in from chan_dahdi.conf
726 unsigned int cancallforward:1;
728 * \brief TRUE if support for call parking is enabled.
729 * \note Set from the "canpark" value read in from chan_dahdi.conf
731 unsigned int canpark:1;
732 /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
733 unsigned int confirmanswer:1;
735 * \brief TRUE if the channel is to be destroyed on hangup.
736 * (Used by pseudo channels.)
738 unsigned int destroy:1;
739 unsigned int didtdd:1; /*!< flag to say its done it once */
740 /*! \brief TRUE if analog type line dialed no digits in Dial() */
741 unsigned int dialednone:1;
742 /*! \brief TRUE if in the process of dialing digits or sending something. */
743 unsigned int dialing:1;
744 /*! \brief TRUE if the transfer capability of the call is digital. */
745 unsigned int digital:1;
746 /*! \brief TRUE if Do-Not-Disturb is enabled. */
748 /*! \brief XXX BOOLEAN Purpose??? */
749 unsigned int echobreak:1;
751 * \brief TRUE if echo cancellation enabled when bridged.
752 * \note Initialized with the "echocancelwhenbridged" value read in from chan_dahdi.conf
753 * \note Disabled if the echo canceller is not setup.
755 unsigned int echocanbridged:1;
756 /*! \brief TRUE if echo cancellation is turned on. */
757 unsigned int echocanon:1;
758 /*! \brief TRUE if a fax tone has already been handled. */
759 unsigned int faxhandled:1;
760 /*! \brief TRUE if dynamic faxbuffers are configured for use, default is OFF */
761 unsigned int usefaxbuffers:1;
762 /*! \brief TRUE while dynamic faxbuffers are in use */
763 unsigned int faxbuffersinuse:1;
764 /*! \brief TRUE if over a radio and dahdi_read() has been called. */
765 unsigned int firstradio:1;
767 * \brief TRUE if the call will be considered "hung up" on a polarity reversal.
768 * \note Set from the "hanguponpolarityswitch" value read in from chan_dahdi.conf
770 unsigned int hanguponpolarityswitch:1;
771 /*! \brief TRUE if DTMF detection needs to be done by hardware. */
772 unsigned int hardwaredtmf:1;
774 * \brief TRUE if the outgoing caller ID is blocked/hidden.
775 * \note Caller ID can be disabled by dialing *67.
776 * \note Caller ID can be enabled by dialing *82.
777 * \note Initialized with the "hidecallerid" value read in from chan_dahdi.conf
779 unsigned int hidecallerid:1;
781 * \brief TRUE if hide just the name not the number for legacy PBX use.
782 * \note Only applies to PRI channels.
783 * \note Set from the "hidecalleridname" value read in from chan_dahdi.conf
785 unsigned int hidecalleridname:1;
786 /*! \brief TRUE if DTMF detection is disabled. */
787 unsigned int ignoredtmf:1;
789 * \brief TRUE if the channel should be answered immediately
790 * without attempting to gather any digits.
791 * \note Set from the "immediate" value read in from chan_dahdi.conf
793 unsigned int immediate:1;
794 /*! \brief TRUE if in an alarm condition. */
795 unsigned int inalarm:1;
796 /*! \brief TRUE if TDD in MATE mode */
798 /*! \brief TRUE if we originated the call leg. */
799 unsigned int outgoing:1;
800 /* unsigned int overlapdial:1; unused and potentially confusing */
802 * \brief TRUE if busy extensions will hear the call-waiting tone
803 * and can use hook-flash to switch between callers.
804 * \note Set from the "callwaiting" value read in from chan_dahdi.conf
806 unsigned int permcallwaiting:1;
808 * \brief TRUE if the outgoing caller ID is blocked/restricted/hidden.
809 * \note Set from the "hidecallerid" value read in from chan_dahdi.conf
811 unsigned int permhidecallerid:1;
813 * \brief TRUE if PRI congestion/busy indications are sent out-of-band.
814 * \note Set from the "priindication" value read in from chan_dahdi.conf
816 unsigned int priindication_oob:1;
818 * \brief TRUE if PRI B channels are always exclusively selected.
819 * \note Set from the "priexclusive" value read in from chan_dahdi.conf
821 unsigned int priexclusive:1;
823 * \brief TRUE if we will pulse dial.
824 * \note Set from the "pulsedial" value read in from chan_dahdi.conf
826 unsigned int pulse:1;
827 /*! \brief TRUE if a pulsed digit was detected. (Pulse dial phone detected) */
828 unsigned int pulsedial:1;
829 unsigned int restartpending:1; /*!< flag to ensure counted only once for restart */
831 * \brief TRUE if caller ID is restricted.
832 * \note Set but not used. Should be deleted. Redundant with permhidecallerid.
833 * \note Set from the "restrictcid" value read in from chan_dahdi.conf
835 unsigned int restrictcid:1;
837 * \brief TRUE if three way calling is enabled
838 * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
840 unsigned int threewaycalling:1;
842 * \brief TRUE if call transfer is enabled
843 * \note For FXS ports (either direct analog or over T1/E1):
844 * Support flash-hook call transfer
845 * \note For digital ports using ISDN PRI protocols:
846 * Support switch-side transfer (called 2BCT, RLT or other names)
847 * \note Set from the "transfer" value read in from chan_dahdi.conf
849 unsigned int transfer:1;
851 * \brief TRUE if caller ID is used on this channel.
852 * \note PRI and SS7 spans will save caller ID from the networking peer.
853 * \note FXS ports will generate the caller ID spill.
854 * \note FXO ports will listen for the caller ID spill.
855 * \note Set from the "usecallerid" value read in from chan_dahdi.conf
857 unsigned int use_callerid:1;
859 * \brief TRUE if we will use the calling presentation setting
860 * from the Asterisk channel for outgoing calls.
861 * \note Only applies to PRI and SS7 channels.
862 * \note Set from the "usecallingpres" value read in from chan_dahdi.conf
864 unsigned int use_callingpres:1;
866 * \brief TRUE if distinctive rings are to be detected.
867 * \note For FXO lines
868 * \note Set indirectly from the "usedistinctiveringdetection" value read in from chan_dahdi.conf
870 unsigned int usedistinctiveringdetection:1;
872 * \brief TRUE if we should use the callerid from incoming call on dahdi transfer.
873 * \note Set from the "useincomingcalleridondahditransfer" value read in from chan_dahdi.conf
875 unsigned int dahditrcallerid:1;
877 * \brief TRUE if allowed to flash-transfer to busy channels.
878 * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
880 unsigned int transfertobusy:1;
882 * \brief TRUE if the FXO port monitors for neon type MWI indications from the other end.
883 * \note Set if the "mwimonitor" value read in contains "neon" from chan_dahdi.conf
885 unsigned int mwimonitor_neon:1;
887 * \brief TRUE if the FXO port monitors for fsk type MWI indications from the other end.
888 * \note Set if the "mwimonitor" value read in contains "fsk" from chan_dahdi.conf
890 unsigned int mwimonitor_fsk:1;
892 * \brief TRUE if the FXO port monitors for rpas precursor to fsk MWI indications from the other end.
893 * \note RPAS - Ring Pulse Alert Signal
894 * \note Set if the "mwimonitor" value read in contains "rpas" from chan_dahdi.conf
896 unsigned int mwimonitor_rpas:1;
897 /*! \brief TRUE if an MWI monitor thread is currently active */
898 unsigned int mwimonitoractive:1;
899 /*! \brief TRUE if a MWI message sending thread is active */
900 unsigned int mwisendactive:1;
902 * \brief TRUE if channel is out of reset and ready
903 * \note Set but not used.
905 unsigned int inservice:1;
907 * \brief TRUE if the channel is locally blocked.
908 * \note Applies to SS7 channels.
910 unsigned int locallyblocked:1;
912 * \brief TRUE if the channel is remotely blocked.
913 * \note Applies to SS7 channels.
915 unsigned int remotelyblocked:1;
916 #if defined(HAVE_PRI) || defined(HAVE_SS7)
918 * \brief XXX BOOLEAN Purpose???
919 * \note Applies to SS7 channels.
922 /*! \brief TRUE if channel is alerting/ringing */
923 unsigned int alerting:1;
924 /*! \brief TRUE if the call has already gone/hungup */
925 unsigned int alreadyhungup:1;
927 * \brief TRUE if this is an idle call
928 * \note Applies to PRI channels.
930 unsigned int isidlecall:1;
932 * \brief TRUE if call is in a proceeding state.
933 * The call has started working its way through the network.
935 unsigned int proceeding:1;
936 /*! \brief TRUE if the call has seen progress through the network. */
937 unsigned int progress:1;
939 * \brief TRUE if this channel is being reset/restarted
940 * \note Applies to PRI channels.
942 unsigned int resetting:1;
944 * \brief TRUE if this channel has received a SETUP_ACKNOWLEDGE
945 * \note Applies to PRI channels.
947 unsigned int setup_ack:1;
950 * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
951 * \note Set from the "usesmdi" value read in from chan_dahdi.conf
953 unsigned int use_smdi:1;
954 struct mwisend_info mwisend_data;
955 /*! \brief The serial port to listen for SMDI data on */
956 struct ast_smdi_interface *smdi_iface;
958 /*! \brief Distinctive Ring data */
959 struct dahdi_distRings drings;
962 * \brief The configured context for incoming calls.
963 * \note The "context" string read in from chan_dahdi.conf
965 char context[AST_MAX_CONTEXT];
967 * \brief Saved context string.
969 char defcontext[AST_MAX_CONTEXT];
970 /*! \brief Extension to use in the dialplan. */
971 char exten[AST_MAX_EXTENSION];
973 * \brief Language configured for calls.
974 * \note The "language" string read in from chan_dahdi.conf
976 char language[MAX_LANGUAGE];
978 * \brief The configured music-on-hold class to use for calls.
979 * \note The "musicclass" or "mohinterpret" or "musiconhold" string read in from chan_dahdi.conf
981 char mohinterpret[MAX_MUSICCLASS];
983 * \brief Sugggested music-on-hold class for peer channel to use for calls.
984 * \note The "mohsuggest" string read in from chan_dahdi.conf
986 char mohsuggest[MAX_MUSICCLASS];
987 char parkinglot[AST_MAX_EXTENSION]; /*!< Parking lot for this channel */
988 #if defined(PRI_ANI) || defined(HAVE_SS7)
989 /*! \brief Automatic Number Identification number (Alternate PRI caller ID number) */
990 char cid_ani[AST_MAX_EXTENSION];
992 /*! \brief Automatic Number Identification code from PRI */
994 /*! \brief Caller ID number from an incoming call. */
995 char cid_num[AST_MAX_EXTENSION];
996 /*! \brief Caller ID Q.931 TON/NPI field values. Set by PRI. Zero otherwise. */
998 /*! \brief Caller ID name from an incoming call. */
999 char cid_name[AST_MAX_EXTENSION];
1000 /*! \brief Last Caller ID number from an incoming call. */
1001 char lastcid_num[AST_MAX_EXTENSION];
1002 /*! \brief Last Caller ID name from an incoming call. */
1003 char lastcid_name[AST_MAX_EXTENSION];
1004 char *origcid_num; /*!< malloced original callerid */
1005 char *origcid_name; /*!< malloced original callerid */
1006 /*! \brief Call waiting number. */
1007 char callwait_num[AST_MAX_EXTENSION];
1008 /*! \brief Call waiting name. */
1009 char callwait_name[AST_MAX_EXTENSION];
1010 /*! \brief Redirecting Directory Number Information Service (RDNIS) number */
1011 char rdnis[AST_MAX_EXTENSION];
1012 /*! \brief Dialed Number Identifier */
1013 char dnid[AST_MAX_EXTENSION];
1015 * \brief Bitmapped groups this belongs to.
1016 * \note The "group" bitmapped group string read in from chan_dahdi.conf
1019 /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
1021 int confno; /*!< Our conference */
1022 int confusers; /*!< Who is using our conference */
1023 int propconfno; /*!< Propagated conference number */
1025 * \brief Bitmapped call groups this belongs to.
1026 * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
1028 ast_group_t callgroup;
1030 * \brief Bitmapped pickup groups this belongs to.
1031 * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
1033 ast_group_t pickupgroup;
1035 * \brief Channel variable list with associated values to set when a channel is created.
1036 * \note The "setvar" strings read in from chan_dahdi.conf
1038 struct ast_variable *vars;
1039 int channel; /*!< Channel Number or CRV */
1040 int span; /*!< Span number */
1041 time_t guardtime; /*!< Must wait this much time before using for new call */
1042 int cid_signalling; /*!< CID signalling type bell202 or v23 */
1043 int cid_start; /*!< CID start indicator, polarity or ring */
1044 int callingpres; /*!< The value of calling presentation that we're going to use when placing a PRI call */
1045 int callwaitingrepeat; /*!< How many samples to wait before repeating call waiting */
1046 int cidcwexpire; /*!< When to expire our muting for CID/CW */
1047 /*! \brief Analog caller ID waveform sample buffer */
1048 unsigned char *cidspill;
1049 /*! \brief Position in the cidspill buffer to send out next. */
1051 /*! \brief Length of the cidspill buffer containing samples. */
1053 /*! \brief Ring timeout timer?? */
1056 * \brief Ring timeout base.
1057 * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
1061 * \brief Number of most significant digits/characters to strip from the dialed number.
1062 * \note Feature is deprecated. Use dialplan logic.
1063 * \note The characters are stripped before the PRI TON/NPI prefix
1064 * characters are processed.
1067 /*! \brief BOOLEAN. XXX Meaning what?? */
1069 /*! \brief Number of call waiting rings. */
1071 /*! \brief Echo cancel parameters. */
1073 struct dahdi_echocanparams head;
1074 struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
1077 * \brief Echo training time. 0 = disabled
1078 * \note Set from the "echotraining" value read in from chan_dahdi.conf
1081 /*! \brief Filled with 'w'. XXX Purpose?? */
1084 * \brief Number of times to see "busy" tone before hanging up.
1085 * \note Set from the "busycount" value read in from chan_dahdi.conf
1089 * \brief Length of "busy" tone on time.
1090 * \note Set from the "busypattern" value read in from chan_dahdi.conf
1092 int busy_tonelength;
1094 * \brief Length of "busy" tone off time.
1095 * \note Set from the "busypattern" value read in from chan_dahdi.conf
1097 int busy_quietlength;
1099 * \brief Bitmapped call progress detection flags. CALLPROGRESS_xxx values.
1100 * \note Bits set from the "callprogress" and "faxdetect" values read in from chan_dahdi.conf
1104 * \brief Number of milliseconds to wait for dialtone.
1105 * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
1107 int waitfordialtone;
1108 struct timeval waitingfordt; /*!< Time we started waiting for dialtone */
1109 struct timeval flashtime; /*!< Last flash-hook time */
1110 /*! \brief Opaque DSP configuration structure. */
1111 struct ast_dsp *dsp;
1112 //int cref; /*!< Call reference number (Not used) */
1113 /*! \brief DAHDI dial operation command struct for ioctl() call. */
1114 struct dahdi_dialoperation dop;
1115 int whichwink; /*!< SIG_FEATDMF_TA Which wink are we on? */
1116 /*! \brief Second part of SIG_FEATDMF_TA wink operation. */
1118 char accountcode[AST_MAX_ACCOUNT_CODE]; /*!< Account code */
1119 int amaflags; /*!< AMA Flags */
1120 struct tdd_state *tdd; /*!< TDD flag */
1121 /*! \brief Accumulated call forwarding number. */
1122 char call_forward[AST_MAX_EXTENSION];
1124 * \brief Voice mailbox location.
1125 * \note Set from the "mailbox" string read in from chan_dahdi.conf
1127 char mailbox[AST_MAX_EXTENSION];
1128 /*! \brief Opaque event subscription parameters for message waiting indication support. */
1129 struct ast_event_sub *mwi_event_sub;
1130 /*! \brief Delayed dialing for E911. Overlap digits for ISDN. */
1132 /*! \brief Time the interface went on-hook. */
1134 /*! \brief TRUE if the FXS port is off-hook */
1135 int fxsoffhookstate;
1136 /*! \brief -1 = unknown, 0 = no messages, 1 = new messages available */
1138 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
1139 struct dahdi_vmwi_info mwisend_setting; /*!< Which VMWI methods to use */
1140 unsigned int mwisend_fsk: 1; /*! Variable for enabling FSK MWI handling in chan_dahdi */
1141 unsigned int mwisend_rpas:1; /*! Variable for enabling Ring Pulse Alert before MWI FSK Spill */
1143 int distinctivering; /*!< Which distinctivering to use */
1144 int cidrings; /*!< Which ring to deliver CID on */
1145 int dtmfrelax; /*!< whether to run in relaxed DTMF mode */
1146 /*! \brief Holding place for event injected from outside normal operation. */
1149 * \brief Minimal time period (ms) between the answer polarity
1150 * switch and hangup polarity switch.
1152 int polarityonanswerdelay;
1153 /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
1154 struct timeval polaritydelaytv;
1156 * \brief Send caller ID after this many rings.
1157 * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
1159 int sendcalleridafter;
1161 /*! \brief DAHDI PRI control parameters */
1162 struct dahdi_pri *pri;
1163 /*! \brief XXX Purpose??? */
1164 struct dahdi_pvt *bearer;
1165 /*! \brief XXX Purpose??? */
1166 struct dahdi_pvt *realcall;
1167 /*! \brief Opaque libpri call control structure */
1169 /*! \brief Channel number in span. */
1171 /*! \brief Logical span number within trunk group */
1174 /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
1176 /*! \brief DSP feature flags: DSP_FEATURE_xxx */
1179 /*! \brief SS7 control parameters */
1180 struct dahdi_ss7 *ss7;
1181 /*! \brief Opaque libss7 call control structure */
1182 struct isup_call *ss7call;
1183 char charge_number[50];
1184 char gen_add_number[50];
1185 char gen_dig_number[50];
1186 char orig_called_num[50];
1187 char redirecting_num[50];
1188 char generic_name[50];
1189 unsigned char gen_add_num_plan;
1190 unsigned char gen_add_nai;
1191 unsigned char gen_add_pres_ind;
1192 unsigned char gen_add_type;
1193 unsigned char gen_dig_type;
1194 unsigned char gen_dig_scheme;
1195 char jip_number[50];
1196 unsigned char lspi_type;
1197 unsigned char lspi_scheme;
1198 unsigned char lspi_context;
1199 char lspi_ident[50];
1200 unsigned int call_ref_ident;
1201 unsigned int call_ref_pc;
1202 unsigned char calling_party_cat;
1204 int cic; /*!< CIC associated with channel */
1205 unsigned int dpc; /*!< CIC's DPC */
1206 unsigned int loopedback:1;
1209 struct dahdi_mfcr2 *mfcr2;
1210 openr2_chan_t *r2chan;
1211 openr2_calling_party_category_t mfcr2_recvd_category;
1212 openr2_calling_party_category_t mfcr2_category;
1213 int mfcr2_dnis_index;
1214 int mfcr2_ani_index;
1216 int mfcr2_answer_pending:1;
1217 int mfcr2_charge_calls:1;
1218 int mfcr2_allow_collect_calls:1;
1219 int mfcr2_forced_release:1;
1220 int mfcr2_dnis_matched:1;
1221 int mfcr2_call_accepted:1;
1222 int mfcr2_accept_on_offer:1;
1224 /*! \brief DTMF digit in progress. 0 when no digit in progress. */
1226 /*! \brief TRUE if confrence is muted. */
1228 } *iflist = NULL, *ifend = NULL;
1230 /*! \brief Channel configuration from chan_dahdi.conf .
1231 * This struct is used for parsing the [channels] section of chan_dahdi.conf.
1232 * Generally there is a field here for every possible configuration item.
1234 * The state of fields is saved along the parsing and whenever a 'channel'
1235 * statement is reached, the current dahdi_chan_conf is used to configure the
1236 * channel (struct dahdi_pvt)
1238 * \see dahdi_chan_init for the default values.
1240 struct dahdi_chan_conf {
1241 struct dahdi_pvt chan;
1243 struct dahdi_pri pri;
1247 struct dahdi_ss7 ss7;
1251 struct dahdi_mfcr2_conf mfcr2;
1253 struct dahdi_params timing;
1254 int is_sig_auto; /*!< Use channel signalling from DAHDI? */
1257 * \brief The serial port to listen for SMDI data on
1258 * \note Set from the "smdiport" string read in from chan_dahdi.conf
1260 char smdi_port[SMDI_MAX_FILENAME_LEN];
1263 /*! returns a new dahdi_chan_conf with default values (by-value) */
1264 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
1266 /* recall that if a field is not included here it is initialized
1267 * to 0 or equivalent
1269 struct dahdi_chan_conf conf = {
1272 .nsf = PRI_NSF_NONE,
1273 .switchtype = PRI_SWITCH_NI2,
1274 .dialplan = PRI_UNKNOWN + 1,
1275 .localdialplan = PRI_NATIONAL_ISDN + 1,
1276 .nodetype = PRI_CPE,
1277 .qsigchannelmapping = DAHDI_CHAN_MAPPING_PHYSICAL,
1282 .internationalprefix = "",
1283 .nationalprefix = "",
1285 .privateprefix = "",
1286 .unknownprefix = "",
1287 .resetinterval = -1,
1292 .called_nai = SS7_NAI_NATIONAL,
1293 .calling_nai = SS7_NAI_NATIONAL,
1294 .internationalprefix = "",
1295 .nationalprefix = "",
1296 .subscriberprefix = "",
1302 .variant = OR2_VAR_ITU,
1303 .mfback_timeout = -1,
1304 .metering_pulse_timeout = -1,
1307 .get_ani_first = -1,
1309 .allow_collect_calls = 0,
1311 .accept_on_offer = 1,
1312 .forced_release = 0,
1314 .immediate_accept = -1,
1317 .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
1318 .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
1322 .context = "default",
1325 .mohinterpret = "default",
1328 .transfertobusy = 1,
1330 .cid_signalling = CID_SIG_BELL,
1331 .cid_start = CID_START_RING,
1332 .dahditrcallerid = 0,
1341 .echocancel.head.tap_length = 1,
1349 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
1352 .polarityonanswerdelay = 600,
1354 .sendcalleridafter = DEFAULT_CIDRINGS,
1356 .buf_policy = DAHDI_POLICY_IMMEDIATE,
1359 .faxbuf_policy = DAHDI_POLICY_IMMEDIATE,
1360 .faxbuf_no = numbufs,
1373 .smdi_port = "/dev/ttyS0",
1380 static struct ast_channel *dahdi_request(const char *type, int format, void *data, int *cause);
1381 static int dahdi_digit_begin(struct ast_channel *ast, char digit);
1382 static int dahdi_digit_end(struct ast_channel *ast, char digit, unsigned int duration);
1383 static int dahdi_sendtext(struct ast_channel *c, const char *text);
1384 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout);
1385 static int dahdi_hangup(struct ast_channel *ast);
1386 static int dahdi_answer(struct ast_channel *ast);
1387 static struct ast_frame *dahdi_read(struct ast_channel *ast);
1388 static int dahdi_write(struct ast_channel *ast, struct ast_frame *frame);
1389 static struct ast_frame *dahdi_exception(struct ast_channel *ast);
1390 static int dahdi_indicate(struct ast_channel *chan, int condition, const void *data, size_t datalen);
1391 static int dahdi_fixup(struct ast_channel *oldchan, struct ast_channel *newchan);
1392 static int dahdi_setoption(struct ast_channel *chan, int option, void *data, int datalen);
1393 static int dahdi_func_read(struct ast_channel *chan, const char *function, char *data, char *buf, size_t len);
1394 static int handle_init_event(struct dahdi_pvt *i, int event);
1396 static const struct ast_channel_tech dahdi_tech = {
1398 .description = tdesc,
1399 .capabilities = AST_FORMAT_SLINEAR | AST_FORMAT_ULAW | AST_FORMAT_ALAW,
1400 .requester = dahdi_request,
1401 .send_digit_begin = dahdi_digit_begin,
1402 .send_digit_end = dahdi_digit_end,
1403 .send_text = dahdi_sendtext,
1405 .hangup = dahdi_hangup,
1406 .answer = dahdi_answer,
1408 .write = dahdi_write,
1409 .bridge = dahdi_bridge,
1410 .exception = dahdi_exception,
1411 .indicate = dahdi_indicate,
1412 .fixup = dahdi_fixup,
1413 .setoption = dahdi_setoption,
1414 .func_channel_read = dahdi_func_read,
1418 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
1420 #define GET_CHANNEL(p) ((p)->channel)
1423 struct dahdi_pvt *round_robin[32];
1425 #if defined(HAVE_PRI)
1426 static inline int pri_grab(struct dahdi_pvt *pvt, struct dahdi_pri *pri)
1429 /* Grab the lock first */
1431 res = ast_mutex_trylock(&pri->lock);
1433 DEADLOCK_AVOIDANCE(&pvt->lock);
1436 /* Then break the poll */
1437 if (pri->master != AST_PTHREADT_NULL)
1438 pthread_kill(pri->master, SIGURG);
1441 #endif /* defined(HAVE_PRI) */
1443 #if defined(HAVE_SS7)
1444 static inline void ss7_rel(struct dahdi_ss7 *ss7)
1446 ast_mutex_unlock(&ss7->lock);
1448 #endif /* defined(HAVE_SS7) */
1450 #if defined(HAVE_SS7)
1451 static inline int ss7_grab(struct dahdi_pvt *pvt, struct dahdi_ss7 *pri)
1454 /* Grab the lock first */
1456 res = ast_mutex_trylock(&pri->lock);
1458 DEADLOCK_AVOIDANCE(&pvt->lock);
1461 /* Then break the poll */
1462 if (pri->master != AST_PTHREADT_NULL)
1463 pthread_kill(pri->master, SIGURG);
1466 #endif /* defined(HAVE_SS7) */
1467 #define NUM_CADENCE_MAX 25
1468 static int num_cadence = 4;
1469 static int user_has_defined_cadences = 0;
1471 static struct dahdi_ring_cadence cadences[NUM_CADENCE_MAX] = {
1472 { { 125, 125, 2000, 4000 } }, /*!< Quick chirp followed by normal ring */
1473 { { 250, 250, 500, 1000, 250, 250, 500, 4000 } }, /*!< British style ring */
1474 { { 125, 125, 125, 125, 125, 4000 } }, /*!< Three short bursts */
1475 { { 1000, 500, 2500, 5000 } }, /*!< Long ring */
1478 /*! \brief cidrings says in which pause to transmit the cid information, where the first pause
1479 * is 1, the second pause is 2 and so on.
1482 static int cidrings[NUM_CADENCE_MAX] = {
1483 2, /*!< Right after first long ring */
1484 4, /*!< Right after long part */
1485 3, /*!< After third chirp */
1486 2, /*!< Second spell */
1489 /* ETSI EN300 659-1 specifies the ring pulse between 200 and 300 mS */
1490 static struct dahdi_ring_cadence AS_RP_cadence = {{250, 10000}};
1492 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
1493 (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
1495 #define CANBUSYDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
1496 #define CANPROGRESSDETECT(p) (ISTRUNK(p) || (p->sig & (SIG_EM | SIG_EM_E1 | SIG_SF)) /* || (p->sig & __DAHDI_SIG_FXO) */)
1498 static int dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok)
1501 if (p->subs[SUB_REAL].owner == ast)
1503 else if (p->subs[SUB_CALLWAIT].owner == ast)
1505 else if (p->subs[SUB_THREEWAY].owner == ast)
1510 ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
1515 static void wakeup_sub(struct dahdi_pvt *p, int a, struct dahdi_pri *pri)
1519 ast_mutex_unlock(&pri->lock);
1522 if (p->subs[a].owner) {
1523 if (ast_channel_trylock(p->subs[a].owner)) {
1524 DEADLOCK_AVOIDANCE(&p->lock);
1526 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
1527 ast_channel_unlock(p->subs[a].owner);
1535 ast_mutex_lock(&pri->lock);
1539 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f, void *data)
1542 struct dahdi_pri *pri = (struct dahdi_pri*) data;
1545 struct dahdi_ss7 *ss7 = (struct dahdi_ss7*) data;
1547 /* We must unlock the PRI to avoid the possibility of a deadlock */
1548 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1555 ast_mutex_unlock(&pri->lock);
1560 ast_mutex_unlock(&ss7->lock);
1570 if (ast_channel_trylock(p->owner)) {
1571 DEADLOCK_AVOIDANCE(&p->lock);
1573 ast_queue_frame(p->owner, f);
1574 ast_channel_unlock(p->owner);
1580 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1587 ast_mutex_lock(&pri->lock);
1592 ast_mutex_lock(&ss7->lock);
1602 static struct ast_channel *dahdi_new(struct dahdi_pvt *, int, int, int, int, int);
1605 static int dahdi_r2_answer(struct dahdi_pvt *p)
1608 /* openr2 1.1.0 and older does not even define OR2_LIB_INTERFACE
1609 * and does not has support for openr2_chan_answer_call_with_mode
1611 #if defined(OR2_LIB_INTERFACE) && OR2_LIB_INTERFACE > 1
1612 const char *double_answer = pbx_builtin_getvar_helper(p->owner, "MFCR2_DOUBLE_ANSWER");
1613 int wants_double_answer = ast_true(double_answer) ? 1 : 0;
1614 if (!double_answer) {
1615 /* this still can result in double answer if the channel context
1616 * was configured that way */
1617 res = openr2_chan_answer_call(p->r2chan);
1618 } else if (wants_double_answer) {
1619 res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_DOUBLE);
1621 res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
1624 res = openr2_chan_answer_call(p->r2chan);
1631 /* should be called with the ast_channel locked */
1632 static openr2_calling_party_category_t dahdi_r2_get_channel_category(struct ast_channel *c)
1634 openr2_calling_party_category_t cat;
1635 const char *catstr = pbx_builtin_getvar_helper(c, "MFCR2_CATEGORY");
1636 struct dahdi_pvt *p = c->tech_pvt;
1637 if (ast_strlen_zero(catstr)) {
1638 ast_debug(1, "No MFC/R2 category specified for chan %s, using default %s\n",
1639 c->name, openr2_proto_get_category_string(p->mfcr2_category));
1640 return p->mfcr2_category;
1642 if ((cat = openr2_proto_get_category(catstr)) == OR2_CALLING_PARTY_CATEGORY_UNKNOWN) {
1643 ast_log(LOG_WARNING, "Invalid category specified '%s' for chan %s, using default %s\n",
1644 catstr, c->name, openr2_proto_get_category_string(p->mfcr2_category));
1645 return p->mfcr2_category;
1647 ast_debug(1, "Using category %s\n", catstr);
1651 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
1653 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1654 ast_mutex_lock(&p->lock);
1656 ast_mutex_unlock(&p->lock);
1657 /* TODO: This can happen when some other thread just finished dahdi_request requesting this very same
1658 interface but has not yet seized the line (dahdi_call), and the far end wins and seize the line,
1659 can we avoid this somehow?, at this point when dahdi_call send the seize, it is likely that since
1660 the other end will see our seize as a forced release and drop the call, we will see an invalid
1661 pattern that will be seen and treated as protocol error. */
1662 ast_log(LOG_ERROR, "Collision of calls on chan %d detected!.\n", openr2_chan_get_number(r2chan));
1666 /* better safe than sorry ... */
1667 p->cid_name[0] = '\0';
1668 p->cid_num[0] = '\0';
1671 p->mfcr2_ani_index = '\0';
1672 p->mfcr2_dnis_index = '\0';
1673 p->mfcr2_dnis_matched = 0;
1674 p->mfcr2_answer_pending = 0;
1675 p->mfcr2_call_accepted = 0;
1676 ast_mutex_unlock(&p->lock);
1677 ast_log(LOG_NOTICE, "New MFC/R2 call detected on chan %d.\n", openr2_chan_get_number(r2chan));
1680 static int get_alarms(struct dahdi_pvt *p);
1681 static void handle_alarms(struct dahdi_pvt *p, int alms);
1682 static void dahdi_r2_on_hardware_alarm(openr2_chan_t *r2chan, int alarm)
1685 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1686 ast_mutex_lock(&p->lock);
1687 p->inalarm = alarm ? 1 : 0;
1689 res = get_alarms(p);
1690 handle_alarms(p, res);
1692 ast_log(LOG_NOTICE, "Alarm cleared on channel %d\n", p->channel);
1693 manager_event(EVENT_FLAG_SYSTEM, "AlarmClear", "Channel: %d\r\n", p->channel);
1695 ast_mutex_unlock(&p->lock);
1698 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
1700 ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
1703 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
1705 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1706 ast_log(LOG_ERROR, "MFC/R2 protocol error on chan %d: %s\n", openr2_chan_get_number(r2chan), openr2_proto_get_error(reason));
1708 p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
1709 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1711 ast_mutex_lock(&p->lock);
1713 ast_mutex_unlock(&p->lock);
1716 static void dahdi_r2_update_monitor_count(struct dahdi_mfcr2 *mfcr2, int increment)
1718 ast_mutex_lock(&mfcr2->monitored_count_lock);
1720 mfcr2->monitored_count++;
1721 if (mfcr2->monitored_count == 1) {
1722 ast_log(LOG_DEBUG, "At least one device needs monitoring, let's wake up the monitor thread.\n");
1723 ast_cond_signal(&mfcr2->do_monitor);
1726 mfcr2->monitored_count--;
1727 if (mfcr2->monitored_count < 0) {
1728 ast_log(LOG_ERROR, "we have a bug here!.\n");
1731 ast_mutex_unlock(&mfcr2->monitored_count_lock);
1734 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
1736 struct dahdi_pvt *p;
1737 struct ast_channel *c;
1738 ast_log(LOG_NOTICE, "MFC/R2 call offered on chan %d. ANI = %s, DNIS = %s, Category = %s\n",
1739 openr2_chan_get_number(r2chan), ani ? ani : "(restricted)", dnis,
1740 openr2_proto_get_category_string(category));
1741 p = openr2_chan_get_client_data(r2chan);
1742 /* if collect calls are not allowed and this is a collect call, reject it! */
1743 if (!p->mfcr2_allow_collect_calls && category == OR2_CALLING_PARTY_CATEGORY_COLLECT_CALL) {
1744 ast_log(LOG_NOTICE, "Rejecting MFC/R2 collect call\n");
1745 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_COLLECT_CALL_REJECTED);
1748 ast_mutex_lock(&p->lock);
1749 p->mfcr2_recvd_category = category;
1750 /* if we're not supposed to use CID, clear whatever we have */
1751 if (!p->use_callerid) {
1752 ast_log(LOG_DEBUG, "No CID allowed in configuration, CID is being cleared!\n");
1756 /* if we're supposed to answer immediately, clear DNIS and set 's' exten */
1757 if (p->immediate || !openr2_context_get_max_dnis(openr2_chan_get_context(r2chan))) {
1758 ast_log(LOG_DEBUG, "Setting exten => s because of immediate or 0 DNIS configured\n");
1762 ast_mutex_unlock(&p->lock);
1763 if (!ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
1764 ast_log(LOG_NOTICE, "MFC/R2 call on channel %d requested non-existent extension '%s' in context '%s'. Rejecting call.\n",
1765 p->channel, p->exten, p->context);
1766 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_UNALLOCATED_NUMBER);
1769 if (!p->mfcr2_accept_on_offer) {
1770 /* The user wants us to start the PBX thread right away without accepting the call first */
1771 c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, 0);
1773 dahdi_r2_update_monitor_count(p->mfcr2, 0);
1774 /* Done here, don't disable reading now since we still need to generate MF tones to accept
1775 the call or reject it and detect the tone off condition of the other end, all of this
1776 will be done in the PBX thread now */
1779 ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
1780 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_OUT_OF_ORDER);
1781 } else if (p->mfcr2_charge_calls) {
1782 ast_log(LOG_DEBUG, "Accepting MFC/R2 call with charge on chan %d\n", p->channel);
1783 openr2_chan_accept_call(r2chan, OR2_CALL_WITH_CHARGE);
1785 ast_log(LOG_DEBUG, "Accepting MFC/R2 call with no charge on chan %d\n", p->channel);
1786 openr2_chan_accept_call(r2chan, OR2_CALL_NO_CHARGE);
1790 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
1792 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1793 ast_log(LOG_NOTICE, "MFC/R2 call end on chan %d\n", p->channel);
1794 ast_mutex_lock(&p->lock);
1796 ast_mutex_unlock(&p->lock);
1799 static void dahdi_enable_ec(struct dahdi_pvt *p);
1800 static void dahdi_r2_on_call_accepted(openr2_chan_t *r2chan, openr2_call_mode_t mode)
1802 struct dahdi_pvt *p = NULL;
1803 struct ast_channel *c = NULL;
1804 ast_log(LOG_NOTICE, "MFC/R2 call has been accepted on chan %d\n", openr2_chan_get_number(r2chan));
1805 p = openr2_chan_get_client_data(r2chan);
1807 p->mfcr2_call_accepted = 1;
1808 /* if it's an incoming call ... */
1809 if (OR2_DIR_BACKWARD == openr2_chan_get_direction(r2chan)) {
1810 /* If accept on offer is not set, it means at this point the PBX thread is already
1811 launched (was launched in the 'on call offered' handler) and therefore this callback
1812 is being executed already in the PBX thread rather than the monitor thread, don't launch
1813 any other thread, just disable the openr2 reading and answer the call if needed */
1814 if (!p->mfcr2_accept_on_offer) {
1815 openr2_chan_disable_read(r2chan);
1816 if (p->mfcr2_answer_pending) {
1817 ast_log(LOG_DEBUG, "Answering MFC/R2 call after accepting it on chan %d\n", openr2_chan_get_number(r2chan));
1822 c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, 0);
1824 dahdi_r2_update_monitor_count(p->mfcr2, 0);
1825 /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
1826 library to forget about it */
1827 openr2_chan_disable_read(r2chan);
1830 ast_log(LOG_WARNING, "Unable to create PBX channel in DAHDI channel %d\n", p->channel);
1831 /* failed to create the channel, bail out and report it as an out of order line */
1832 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_OUT_OF_ORDER);
1835 /* this is an outgoing call, no need to launch the PBX thread, most likely we're in one already */
1836 ast_log(LOG_NOTICE, "Call accepted on forward channel %d\n", p->channel);
1837 p->subs[SUB_REAL].needringing = 1;
1839 /* chan_dahdi will take care of reading from now on in the PBX thread, tell the
1840 library to forget about it */
1841 openr2_chan_disable_read(r2chan);
1844 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
1846 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1847 ast_log(LOG_DEBUG, "MFC/R2 call has been answered on chan %d\n", openr2_chan_get_number(r2chan));
1848 p->subs[SUB_REAL].needanswer = 1;
1851 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
1853 /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
1856 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
1859 case OR2_CAUSE_BUSY_NUMBER:
1860 return AST_CAUSE_BUSY;
1861 case OR2_CAUSE_NETWORK_CONGESTION:
1862 return AST_CAUSE_CONGESTION;
1863 case OR2_CAUSE_OUT_OF_ORDER:
1864 return AST_CAUSE_DESTINATION_OUT_OF_ORDER;
1865 case OR2_CAUSE_UNALLOCATED_NUMBER:
1866 return AST_CAUSE_UNREGISTERED;
1867 case OR2_CAUSE_NO_ANSWER:
1868 return AST_CAUSE_NO_ANSWER;
1869 case OR2_CAUSE_NORMAL_CLEARING:
1870 return AST_CAUSE_NORMAL_CLEARING;
1871 case OR2_CAUSE_UNSPECIFIED:
1873 return AST_CAUSE_NOTDEFINED;
1877 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
1879 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1880 ast_verb(3, "MFC/R2 call disconnected on chan %d\n", openr2_chan_get_number(r2chan));
1881 ast_mutex_lock(&p->lock);
1883 ast_mutex_unlock(&p->lock);
1884 /* no owner, therefore we can't use dahdi_hangup to disconnect, do it right now */
1885 openr2_chan_disconnect_call(r2chan, OR2_CAUSE_NORMAL_CLEARING);
1888 /* when we have an owner we don't call openr2_chan_disconnect_call here, that will
1889 be done in dahdi_hangup */
1890 if (p->owner->_state == AST_STATE_UP) {
1891 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1892 ast_mutex_unlock(&p->lock);
1893 } else if (openr2_chan_get_direction(r2chan) == OR2_DIR_FORWARD) {
1894 /* being the forward side we must report what happened to the call to whoever requested it */
1896 case OR2_CAUSE_BUSY_NUMBER:
1897 p->subs[SUB_REAL].needbusy = 1;
1899 case OR2_CAUSE_NETWORK_CONGESTION:
1900 case OR2_CAUSE_OUT_OF_ORDER:
1901 case OR2_CAUSE_UNALLOCATED_NUMBER:
1902 case OR2_CAUSE_NO_ANSWER:
1903 case OR2_CAUSE_UNSPECIFIED:
1904 case OR2_CAUSE_NORMAL_CLEARING:
1905 p->subs[SUB_REAL].needcongestion = 1;
1908 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1910 ast_mutex_unlock(&p->lock);
1912 ast_mutex_unlock(&p->lock);
1913 /* being the backward side and not UP yet, we only need to request hangup */
1914 /* TODO: what about doing this same thing when were AST_STATE_UP? */
1915 ast_queue_hangup_with_cause(p->owner, dahdi_r2_cause_to_ast_cause(cause));
1919 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
1922 case OR2_LOG_NOTICE:
1923 ast_log(LOG_NOTICE, "%s", logmessage);
1925 case OR2_LOG_WARNING:
1926 ast_log(LOG_WARNING, "%s", logmessage);
1929 ast_log(LOG_ERROR, "%s", logmessage);
1931 case OR2_LOG_STACK_TRACE:
1932 case OR2_LOG_MF_TRACE:
1933 case OR2_LOG_CAS_TRACE:
1935 case OR2_LOG_EX_DEBUG:
1936 ast_log(LOG_DEBUG, "%s", logmessage);
1939 ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
1940 ast_log(LOG_DEBUG, "%s", logmessage);
1945 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
1947 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1948 ast_mutex_lock(&p->lock);
1949 p->remotelyblocked = 1;
1950 ast_mutex_unlock(&p->lock);
1951 ast_log(LOG_NOTICE, "Far end blocked on chan %d\n", openr2_chan_get_number(r2chan));
1954 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
1956 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1957 ast_mutex_lock(&p->lock);
1958 p->remotelyblocked = 0;
1959 ast_mutex_unlock(&p->lock);
1960 ast_log(LOG_NOTICE, "Far end unblocked on chan %d\n", openr2_chan_get_number(r2chan));
1963 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
1964 __attribute__((format (printf, 3, 0)));
1965 static void dahdi_r2_on_context_log(openr2_context_t *r2context, openr2_log_level_t level, const char *fmt, va_list ap)
1967 #define CONTEXT_TAG "Context - "
1969 char completemsg[sizeof(logmsg) + sizeof(CONTEXT_TAG) - 1];
1970 vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
1971 snprintf(completemsg, sizeof(completemsg), CONTEXT_TAG "%s", logmsg);
1972 dahdi_r2_write_log(level, completemsg);
1976 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
1977 __attribute__((format (printf, 3, 0)));
1978 static void dahdi_r2_on_chan_log(openr2_chan_t *r2chan, openr2_log_level_t level, const char *fmt, va_list ap)
1980 #define CHAN_TAG "Chan "
1982 char completemsg[sizeof(logmsg) + sizeof(CHAN_TAG) - 1];
1983 vsnprintf(logmsg, sizeof(logmsg), fmt, ap);
1984 snprintf(completemsg, sizeof(completemsg), CHAN_TAG "%d - %s", openr2_chan_get_number(r2chan), logmsg);
1985 dahdi_r2_write_log(level, completemsg);
1988 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
1990 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1991 /* if 'immediate' is set, let's stop requesting DNIS */
1995 p->exten[p->mfcr2_dnis_index] = digit;
1996 p->rdnis[p->mfcr2_dnis_index] = digit;
1997 p->mfcr2_dnis_index++;
1998 p->exten[p->mfcr2_dnis_index] = 0;
1999 p->rdnis[p->mfcr2_dnis_index] = 0;
2000 /* if the DNIS is a match and cannot match more, stop requesting DNIS */
2001 if ((p->mfcr2_dnis_matched ||
2002 (ast_exists_extension(NULL, p->context, p->exten, 1, p->cid_num) && (p->mfcr2_dnis_matched = 1))) &&
2003 !ast_matchmore_extension(NULL, p->context, p->exten, 1, p->cid_num)) {
2006 /* otherwise keep going */
2010 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
2012 struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
2013 p->cid_num[p->mfcr2_ani_index] = digit;
2014 p->cid_name[p->mfcr2_ani_index] = digit;
2015 p->mfcr2_ani_index++;
2016 p->cid_num[p->mfcr2_ani_index] = 0;
2017 p->cid_name[p->mfcr2_ani_index] = 0;
2020 static openr2_event_interface_t dahdi_r2_event_iface = {
2021 .on_call_init = dahdi_r2_on_call_init,
2022 .on_call_offered = dahdi_r2_on_call_offered,
2023 .on_call_accepted = dahdi_r2_on_call_accepted,
2024 .on_call_answered = dahdi_r2_on_call_answered,
2025 .on_call_disconnect = dahdi_r2_on_call_disconnect,
2026 .on_call_end = dahdi_r2_on_call_end,
2027 .on_call_read = dahdi_r2_on_call_read,
2028 .on_hardware_alarm = dahdi_r2_on_hardware_alarm,
2029 .on_os_error = dahdi_r2_on_os_error,
2030 .on_protocol_error = dahdi_r2_on_protocol_error,
2031 .on_line_blocked = dahdi_r2_on_line_blocked,
2032 .on_line_idle = dahdi_r2_on_line_idle,
2033 /* cast seems to be needed to get rid of the annoying warning regarding format attribute */
2034 .on_context_log = (openr2_handle_context_logging_func)dahdi_r2_on_context_log,
2035 .on_dnis_digit_received = dahdi_r2_on_dnis_digit_received,
2036 .on_ani_digit_received = dahdi_r2_on_ani_digit_received,
2037 /* so far we do nothing with billing pulses */
2038 .on_billing_pulse_received = NULL
2041 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
2043 return AST_ALAW(sample);
2046 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
2048 return AST_LIN2A(sample);
2051 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
2052 dahdi_r2_alaw_to_linear,
2053 dahdi_r2_linear_to_alaw
2056 #endif /* HAVE_OPENR2 */
2058 static int restore_gains(struct dahdi_pvt *p);
2060 static void swap_subs(struct dahdi_pvt *p, int a, int b)
2064 struct ast_channel *towner;
2066 ast_debug(1, "Swapping %d and %d\n", a, b);
2068 tchan = p->subs[a].chan;
2069 towner = p->subs[a].owner;
2070 tinthreeway = p->subs[a].inthreeway;
2072 p->subs[a].chan = p->subs[b].chan;
2073 p->subs[a].owner = p->subs[b].owner;
2074 p->subs[a].inthreeway = p->subs[b].inthreeway;
2076 p->subs[b].chan = tchan;
2077 p->subs[b].owner = towner;
2078 p->subs[b].inthreeway = tinthreeway;
2080 if (p->subs[a].owner)
2081 ast_channel_set_fd(p->subs[a].owner, 0, p->subs[a].dfd);
2082 if (p->subs[b].owner)
2083 ast_channel_set_fd(p->subs[b].owner, 0, p->subs[b].dfd);
2084 wakeup_sub(p, a, NULL);
2085 wakeup_sub(p, b, NULL);
2088 static int dahdi_open(char *fn)
2096 for (x = 0; x < strlen(fn); x++) {
2097 if (!isdigit(fn[x])) {
2105 ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
2108 fn = "/dev/dahdi/channel";
2110 fd = open(fn, O_RDWR | O_NONBLOCK);
2112 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
2116 if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
2120 ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
2125 if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
2126 ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs, strerror(errno));
2135 static void dahdi_close(int fd)
2141 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
2143 dahdi_close(chan_pvt->subs[sub_num].dfd);
2144 chan_pvt->subs[sub_num].dfd = -1;
2147 #if defined(HAVE_PRI)
2148 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
2150 dahdi_close(pri->fds[fd_num]);
2151 pri->fds[fd_num] = -1;
2153 #endif /* defined(HAVE_PRI) */
2155 #if defined(HAVE_SS7)
2156 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
2158 dahdi_close(ss7->fds[fd_num]);
2159 ss7->fds[fd_num] = -1;
2161 #endif /* defined(HAVE_SS7) */
2163 static int dahdi_setlinear(int dfd, int linear)
2166 res = ioctl(dfd, DAHDI_SETLINEAR, &linear);
2173 static int alloc_sub(struct dahdi_pvt *p, int x)
2175 struct dahdi_bufferinfo bi;
2177 if (p->subs[x].dfd >= 0) {
2178 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
2182 p->subs[x].dfd = dahdi_open("/dev/dahdi/pseudo");
2183 if (p->subs[x].dfd <= -1) {
2184 ast_log(LOG_WARNING, "Unable to open pseudo channel: %s\n", strerror(errno));
2188 res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
2190 bi.txbufpolicy = p->buf_policy;
2191 bi.rxbufpolicy = p->buf_policy;
2192 bi.numbufs = p->buf_no;
2193 res = ioctl(p->subs[x].dfd, DAHDI_SET_BUFINFO, &bi);
2195 ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
2198 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
2200 if (ioctl(p->subs[x].dfd, DAHDI_CHANNO, &p->subs[x].chan) == 1) {
2201 ast_log(LOG_WARNING, "Unable to get channel number for pseudo channel on FD %d: %s\n", p->subs[x].dfd, strerror(errno));
2202 dahdi_close_sub(p, x);
2203 p->subs[x].dfd = -1;
2206 ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
2210 static int unalloc_sub(struct dahdi_pvt *p, int x)
2213 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
2216 ast_debug(1, "Released sub %d of channel %d\n", x, p->channel);
2217 dahdi_close_sub(p, x);
2218 p->subs[x].linear = 0;
2219 p->subs[x].chan = 0;
2220 p->subs[x].owner = NULL;
2221 p->subs[x].inthreeway = 0;
2222 p->polarity = POLARITY_IDLE;
2223 memset(&p->subs[x].curconf, 0, sizeof(p->subs[x].curconf));
2227 static int digit_to_dtmfindex(char digit)
2230 return DAHDI_TONE_DTMF_BASE + (digit - '0');
2231 else if (digit >= 'A' && digit <= 'D')
2232 return DAHDI_TONE_DTMF_A + (digit - 'A');
2233 else if (digit >= 'a' && digit <= 'd')
2234 return DAHDI_TONE_DTMF_A + (digit - 'a');
2235 else if (digit == '*')
2236 return DAHDI_TONE_DTMF_s;
2237 else if (digit == '#')
2238 return DAHDI_TONE_DTMF_p;
2243 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
2245 struct dahdi_pvt *pvt;
2249 pvt = chan->tech_pvt;
2251 ast_mutex_lock(&pvt->lock);
2253 idx = dahdi_get_index(chan, pvt, 0);
2255 if ((idx != SUB_REAL) || !pvt->owner)
2259 if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
2260 && (chan->_state == AST_STATE_DIALING) && !pvt->proceeding) {
2261 if (pvt->setup_ack) {
2262 if (!pri_grab(pvt, pvt->pri)) {
2263 pri_information(pvt->pri->pri, pvt->call, digit);
2266 ast_log(LOG_WARNING, "Unable to grab PRI on span %d\n", pvt->span);
2267 } else if (strlen(pvt->dialdest) < sizeof(pvt->dialdest) - 1) {
2269 ast_debug(1, "Queueing digit '%c' since setup_ack not yet received\n", digit);
2270 res = strlen(pvt->dialdest);
2271 pvt->dialdest[res++] = digit;
2272 pvt->dialdest[res] = '\0';
2277 if ((dtmf = digit_to_dtmfindex(digit)) == -1)
2280 if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
2282 struct dahdi_dialoperation zo = {
2283 .op = DAHDI_DIAL_OP_APPEND,
2286 zo.dialstr[0] = 'T';
2287 zo.dialstr[1] = digit;
2288 zo.dialstr[2] = '\0';
2289 if ((res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_DIAL, &zo)))
2290 ast_log(LOG_WARNING, "Couldn't dial digit %c: %s\n", digit, strerror(errno));
2294 ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
2296 pvt->begindigit = digit;
2300 ast_mutex_unlock(&pvt->lock);
2305 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
2307 struct dahdi_pvt *pvt;
2312 pvt = chan->tech_pvt;
2314 ast_mutex_lock(&pvt->lock);
2316 idx = dahdi_get_index(chan, pvt, 0);
2318 if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
2322 /* This means that the digit was already sent via PRI signalling */
2323 if (((pvt->sig == SIG_PRI) || (pvt->sig == SIG_BRI) || (pvt->sig == SIG_BRI_PTMP))
2324 && !pvt->begindigit)
2328 if (pvt->begindigit) {
2330 ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
2331 res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
2333 pvt->begindigit = 0;
2337 ast_mutex_unlock(&pvt->lock);
2342 static char *events[] = {
2355 "Hook Transition Complete",
2360 "Polarity Reversal",
2368 { DAHDI_ALARM_RED, "Red Alarm" },
2369 { DAHDI_ALARM_YELLOW, "Yellow Alarm" },
2370 { DAHDI_ALARM_BLUE, "Blue Alarm" },
2371 { DAHDI_ALARM_RECOVER, "Recovering" },
2372 { DAHDI_ALARM_LOOPBACK, "Loopback" },
2373 { DAHDI_ALARM_NOTOPEN, "Not Open" },
2374 { DAHDI_ALARM_NONE, "None" },
2377 static char *alarm2str(int alm)
2380 for (x = 0; x < ARRAY_LEN(alarms); x++) {
2381 if (alarms[x].alarm & alm)
2382 return alarms[x].name;
2384 return alm ? "Unknown Alarm" : "No Alarm";
2387 static char *event2str(int event)
2389 static char buf[256];
2390 if ((event < (ARRAY_LEN(events))) && (event > -1))
2391 return events[event];
2392 sprintf(buf, "Event %d", event); /* safe */
2397 static char *dialplan2str(int dialplan)
2399 if (dialplan == -1 || dialplan == -2) {
2400 return("Dynamically set dialplan in ISDN");
2402 return (pri_plan2str(dialplan));
2406 static char *dahdi_sig2str(int sig)
2408 static char buf[256];
2411 return "E & M Immediate";
2413 return "E & M Wink";
2417 return "Feature Group D (DTMF)";
2419 return "Feature Group D (MF)";
2420 case SIG_FEATDMF_TA:
2421 return "Feature Groud D (MF) Tandem Access";
2423 return "Feature Group B (MF)";
2427 return "FGC/CAMA (Dialpulse)";
2428 case SIG_FGC_CAMAMF:
2429 return "FGC/CAMA (MF)";
2431 return "FXS Loopstart";
2433 return "FXS Groundstart";
2435 return "FXS Kewlstart";
2437 return "FXO Loopstart";
2439 return "FXO Groundstart";
2441 return "FXO Kewlstart";
2445 return "ISDN BRI Point to Point";
2447 return "ISDN BRI Point to MultiPoint";
2453 return "SF (Tone) Immediate";
2455 return "SF (Tone) Wink";
2457 return "SF (Tone) with Feature Group D (DTMF)";
2458 case SIG_SF_FEATDMF:
2459 return "SF (Tone) with Feature Group D (MF)";
2461 return "SF (Tone) with Feature Group B (MF)";
2462 case SIG_GR303FXOKS:
2463 return "GR-303 with FXOKS";
2464 case SIG_GR303FXSKS:
2465 return "GR-303 with FXSKS";
2469 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
2474 #define sig2str dahdi_sig2str
2476 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
2478 /* If the conference already exists, and we're already in it
2479 don't bother doing anything */
2480 struct dahdi_confinfo zi;
2482 memset(&zi, 0, sizeof(zi));
2485 if (slavechannel > 0) {
2486 /* If we have only one slave, do a digital mon */
2487 zi.confmode = DAHDI_CONF_DIGITALMON;
2488 zi.confno = slavechannel;
2491 /* Real-side and pseudo-side both participate in conference */
2492 zi.confmode = DAHDI_CONF_REALANDPSEUDO | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER |
2493 DAHDI_CONF_PSEUDO_TALKER | DAHDI_CONF_PSEUDO_LISTENER;
2495 zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
2496 zi.confno = p->confno;
2498 if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
2502 if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
2503 ast_log(LOG_WARNING, "Failed to add %d to conference %d/%d: %s\n", c->dfd, zi.confmode, zi.confno, strerror(errno));
2506 if (slavechannel < 1) {
2507 p->confno = zi.confno;
2509 memcpy(&c->curconf, &zi, sizeof(c->curconf));
2510 ast_debug(1, "Added %d to conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
2514 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
2516 /* If they're listening to our channel, they're ours */
2517 if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
2519 /* If they're a talker on our (allocated) conference, they're ours */
2520 if ((p->confno > 0) && (p->confno == c->curconf.confno) && (c->curconf.confmode & DAHDI_CONF_TALKER))
2525 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
2527 struct dahdi_confinfo zi;
2528 if (/* Can't delete if there's no dfd */
2530 /* Don't delete from the conference if it's not our conference */
2532 /* Don't delete if we don't think it's conferenced at all (implied) */
2534 memset(&zi, 0, sizeof(zi));
2535 if (ioctl(c->dfd, DAHDI_SETCONF, &zi)) {
2536 ast_log(LOG_WARNING, "Failed to drop %d from conference %d/%d: %s\n", c->dfd, c->curconf.confmode, c->curconf.confno, strerror(errno));
2539 ast_debug(1, "Removed %d from conference %d/%d\n", c->dfd, c->curconf.confmode, c->curconf.confno);
2540 memcpy(&c->curconf, &zi, sizeof(c->curconf));
2544 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
2548 struct dahdi_pvt *slave = NULL;
2549 /* Start out optimistic */
2551 /* Update conference state in a stateless fashion */
2552 for (x = 0; x < 3; x++) {
2553 /* Any three-way calling makes slave native mode *definitely* out
2555 if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
2558 /* If we don't have any 3-way calls, check to see if we have
2559 precisely one slave */
2560 if (useslavenative) {
2561 for (x = 0; x < MAX_SLAVES; x++) {
2564 /* Whoops already have a slave! No
2565 slave native and stop right away */
2570 /* We have one slave so far */
2571 slave = p->slaves[x];
2576 /* If no slave, slave native definitely out */
2579 else if (slave->law != p->law) {
2585 return useslavenative;
2588 static int reset_conf(struct dahdi_pvt *p)
2591 memset(&p->subs[SUB_REAL].curconf, 0, sizeof(p->subs[SUB_REAL].curconf));
2592 if (p->subs[SUB_REAL].dfd > -1) {
2593 struct dahdi_confinfo zi;
2595 memset(&zi, 0, sizeof(zi));
2596 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &zi))
2597 ast_log(LOG_WARNING, "Failed to reset conferencing on channel %d: %s\n", p->channel, strerror(errno));
2602 static int update_conf(struct dahdi_pvt *p)
2607 struct dahdi_pvt *slave = NULL;
2609 useslavenative = isslavenative(p, &slave);
2610 /* Start with the obvious, general stuff */
2611 for (x = 0; x < 3; x++) {
2612 /* Look for three way calls */
2613 if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway) {
2614 conf_add(p, &p->subs[x], x, 0);
2617 conf_del(p, &p->subs[x], x);
2620 /* If we have a slave, add him to our conference now. or DAX
2621 if this is slave native */
2622 for (x = 0; x < MAX_SLAVES; x++) {
2625 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
2627 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
2632 /* If we're supposed to be in there, do so now */
2633 if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
2635 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
2637 conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
2641 /* If we have a master, add ourselves to his conference */
2643 if (isslavenative(p->master, NULL)) {
2644 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
2646 conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
2650 /* Nobody is left (or should be left) in our conference.
2654 ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
2658 static void dahdi_enable_ec(struct dahdi_pvt *p)
2665 ast_debug(1, "Echo cancellation already on\n");
2669 ast_debug(1, "Echo cancellation isn't required on digital connection\n");
2672 if (p->echocancel.head.tap_length) {
2673 if ((p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP) || (p->sig == SIG_PRI) || (p->sig == SIG_SS7)) {
2675 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
2677 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
2679 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
2681 ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
2684 ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
2687 ast_debug(1, "No echo cancellation requested\n");
2690 static void dahdi_train_ec(struct dahdi_pvt *p)
2695 if (p && p->echocanon && p->echotraining) {
2696 x = p->echotraining;
2697 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
2699 ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
2701 ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
2703 ast_debug(1, "No echo training requested\n");
2707 static void dahdi_disable_ec(struct dahdi_pvt *p)
2712 struct dahdi_echocanparams ecp = { .tap_length = 0 };
2714 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
2717 ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
2719 ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
2725 static void fill_txgain(struct dahdi_gains *g, float gain, int law)
2729 float linear_gain = pow(10.0, gain / 20.0);
2732 case DAHDI_LAW_ALAW:
2733 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
2735 k = (int) (((float) AST_ALAW(j)) * linear_gain);
2736 if (k > 32767) k = 32767;
2737 if (k < -32767) k = -32767;
2738 g->txgain[j] = AST_LIN2A(k);
2744 case DAHDI_LAW_MULAW:
2745 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
2747 k = (int) (((float) AST_MULAW(j)) * linear_gain);
2748 if (k > 32767) k = 32767;
2749 if (k < -32767) k = -32767;
2750 g->txgain[j] = AST_LIN2MU(k);
2759 static void fill_rxgain(struct dahdi_gains *g, float gain, int law)
2763 float linear_gain = pow(10.0, gain / 20.0);
2766 case DAHDI_LAW_ALAW:
2767 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
2769 k = (int) (((float) AST_ALAW(j)) * linear_gain);
2770 if (k > 32767) k = 32767;
2771 if (k < -32767) k = -32767;
2772 g->rxgain[j] = AST_LIN2A(k);
2778 case DAHDI_LAW_MULAW:
2779 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
2781 k = (int) (((float) AST_MULAW(j)) * linear_gain);
2782 if (k > 32767) k = 32767;
2783 if (k < -32767) k = -32767;
2784 g->rxgain[j] = AST_LIN2MU(k);
2793 static int set_actual_txgain(int fd, int chan, float gain, int law)
2795 struct dahdi_gains g;
2798 memset(&g, 0, sizeof(g));
2800 res = ioctl(fd, DAHDI_GETGAINS, &g);
2802 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
2806 fill_txgain(&g, gain, law);
2808 return ioctl(fd, DAHDI_SETGAINS, &g);
2811 static int set_actual_rxgain(int fd, int chan, float gain, int law)
2813 struct dahdi_gains g;
2816 memset(&g, 0, sizeof(g));
2818 res = ioctl(fd, DAHDI_GETGAINS, &g);
2820 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
2824 fill_rxgain(&g, gain, law);
2826 return ioctl(fd, DAHDI_SETGAINS, &g);
2829 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
2831 return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
2834 static int bump_gains(struct dahdi_pvt *p)
2838 /* Bump receive gain by value stored in cid_rxgain */
2839 res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain + p->cid_rxgain, p->txgain, p->law);
2841 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
2848 static int restore_gains(struct dahdi_pvt *p)
2852 res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
2854 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
2861 static inline int dahdi_set_hook(int fd, int hs)
2866 res = ioctl(fd, DAHDI_HOOK, &x);
2869 if (errno == EINPROGRESS)
2871 ast_log(LOG_WARNING, "DAHDI hook failed returned %d (trying %d): %s\n", res, hs, strerror(errno));
2872 /* will expectedly fail if phone is off hook during operation, such as during a restart */
2878 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
2882 if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
2884 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
2886 ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n", p->channel, strerror(errno));
2888 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
2890 ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
2894 static int save_conference(struct dahdi_pvt *p)
2896 struct dahdi_confinfo c;
2898 if (p->saveconf.confmode) {
2899 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
2902 p->saveconf.chan = 0;
2903 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
2905 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
2906 p->saveconf.confmode = 0;
2909 memset(&c, 0, sizeof(c));
2910 c.confmode = DAHDI_CONF_NORMAL;
2911 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
2913 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
2916 ast_debug(1, "Disabled conferencing\n");
2921 * \brief Send MWI state change
2923 * \arg mailbox_full This is the mailbox associated with the FXO line that the
2924 * MWI state has changed on.
2925 * \arg thereornot This argument should simply be set to 1 or 0, to indicate
2926 * whether there are messages waiting or not.
2930 * This function does two things:
2932 * 1) It generates an internal Asterisk event notifying any other module that
2933 * cares about MWI that the state of a mailbox has changed.
2935 * 2) It runs the script specified by the mwimonitornotify option to allow
2936 * some custom handling of the state change.
2938 static void notify_message(char *mailbox_full, int thereornot)
2940 char s[sizeof(mwimonitornotify) + 80];
2941 struct ast_event *event;
2942 char *mailbox, *context;
2944 /* Strip off @default */
2945 context = mailbox = ast_strdupa(mailbox_full);
2946 strsep(&context, "@");
2947 if (ast_strlen_zero(context))
2948 context = "default";
2950 if (!(event = ast_event_new(AST_EVENT_MWI,
2951 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
2952 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
2953 AST_EVENT_IE_NEWMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
2954 AST_EVENT_IE_OLDMSGS, AST_EVENT_IE_PLTYPE_UINT, thereornot,
2955 AST_EVENT_IE_END))) {
2959 ast_event_queue_and_cache(event);
2961 if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
2962 snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
2967 static int restore_conference(struct dahdi_pvt *p)
2970 if (p->saveconf.confmode) {
2971 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
2972 p->saveconf.confmode = 0;
2974 ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
2978 ast_debug(1, "Restored conferencing\n");
2982 static int send_callerid(struct dahdi_pvt *p);
2984 static int send_cwcidspill(struct dahdi_pvt *p)
2988 if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
2990 p->cidlen = ast_callerid_callwaiting_generate(p->cidspill, p->callwait_name, p->callwait_num, AST_LAW(p));
2991 /* Make sure we account for the end */
2992 p->cidlen += READ_SIZE * 4;
2995 ast_verb(3, "CPE supports Call Waiting Caller*ID. Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
2999 static int has_voicemail(struct dahdi_pvt *p)
3002 struct ast_event *event;
3003 char *mailbox, *context;
3005 mailbox = context = ast_strdupa(p->mailbox);
3006 strsep(&context, "@");
3007 if (ast_strlen_zero(context))
3008 context = "default";
3010 event = ast_event_get_cached(AST_EVENT_MWI,
3011 AST_EVENT_IE_MAILBOX, AST_EVENT_IE_PLTYPE_STR, mailbox,
3012 AST_EVENT_IE_CONTEXT, AST_EVENT_IE_PLTYPE_STR, context,
3016 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
3017 ast_event_destroy(event);
3019 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
3024 static int send_callerid(struct dahdi_pvt *p)
3026 /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
3028 /* Take out of linear mode if necessary */
3029 if (p->subs[SUB_REAL].linear) {
3030 p->subs[SUB_REAL].linear = 0;
3031 dahdi_setlinear(p->subs[SUB_REAL].dfd, 0);
3033 while (p->cidpos < p->cidlen) {
3034 res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
3036 if (errno == EAGAIN)
3039 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
3047 ast_free(p->cidspill);
3049 if (p->callwaitcas) {
3050 /* Wait for CID/CW to expire */
3051 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
3053 restore_conference(p);
3057 static int dahdi_callwait(struct ast_channel *ast)
3059 struct dahdi_pvt *p = ast->tech_pvt;
3060 p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
3062 ast_log(LOG_WARNING, "Spill already exists?!?\n");
3063 ast_free(p->cidspill);
3065 if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
3069 memset(p->cidspill, 0x7f, 2400 + 600 + READ_SIZE * 4);
3070 if (!p->callwaitrings && p->callwaitingcallerid) {
3071 ast_gen_cas(p->cidspill, 1, 2400 + 680, AST_LAW(p));
3073 p->cidlen = 2400 + 680 + READ_SIZE * 4;
3075 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
3077 p->cidlen = 2400 + READ_SIZE * 4;
3085 #if defined(HAVE_SS7)
3086 static unsigned char cid_pres2ss7pres(int cid_pres)
3088 return (cid_pres >> 5) & 0x03;
3090 #endif /* defined(HAVE_SS7) */
3092 #if defined(HAVE_SS7)
3093 static unsigned char cid_pres2ss7screen(int cid_pres)
3095 return cid_pres & 0x03;
3097 #endif /* defined(HAVE_SS7) */
3099 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
3101 struct dahdi_pvt *p = ast->tech_pvt;
3102 int x, res, idx,mysig;
3107 char dest[256]; /* must be same length as p->dialdest */
3108 ast_mutex_lock(&p->lock);
3109 ast_copy_string(dest, rdest, sizeof(dest));
3110 ast_copy_string(p->dialdest, rdest, sizeof(p->dialdest));
3111 if ((ast->_state == AST_STATE_BUSY)) {
3112 p->subs[SUB_REAL].needbusy = 1;
3113 ast_mutex_unlock(&p->lock);
3116 if ((ast->_state != AST_STATE_DOWN) && (ast->_state != AST_STATE_RESERVED)) {
3117 ast_log(LOG_WARNING, "dahdi_call called on %s, neither down nor reserved\n", ast->name);
3118 ast_mutex_unlock(&p->lock);
3121 p->waitingfordt.tv_sec = 0;
3123 if ((p->radio || (p->oprmode < 0))) /* if a radio channel, up immediately */
3125 /* Special pseudo -- automatically up */
3126 ast_setstate(ast, AST_STATE_UP);
3127 ast_mutex_unlock(&p->lock);
3130 x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
3131 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
3133 ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
3136 set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
3139 if (p->outsigmod > -1)
3140 mysig = p->outsigmod;
3146 if (p->owner == ast) {
3147 /* Normal ring, on hook */
3149 /* Don't send audio while on hook, until the call is answered */
3151 if (p->use_callerid) {
3152 /* Generate the Caller-ID spill if desired */
3154 ast_log(LOG_WARNING, "cidspill already exists??\n");
3155 ast_free(p->cidspill);
3158 if ((p->cidspill = ast_malloc(MAX_CALLERID_SIZE))) {
3159 p->cidlen = ast_callerid_generate(p->cidspill, ast->cid.cid_name, ast->cid.cid_num, AST_LAW(p));
3164 /* Choose proper cadence */
3165 if ((p->distinctivering > 0) && (p->distinctivering <= num_cadence)) {
3166 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, &cadences[p->distinctivering - 1]))
3167 ast_log(LOG_WARNING, "Unable to set distinctive ring cadence %d on '%s': %s\n", p->distinctivering, ast->name, strerror(errno));
3168 p->cidrings = cidrings[p->distinctivering - 1];
3170 if (ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCADENCE, NULL))
3171 ast_log(LOG_WARNING, "Unable to reset default ring on '%s': %s\n", ast->name, strerror(errno));
3172 p->cidrings = p->sendcalleridafter;