Merged revisions 185952 via svnmerge from
[asterisk/asterisk.git] / channels / chan_dahdi.c
1 /*
2  * Asterisk -- An open source telephony toolkit.
3  *
4  * Copyright (C) 1999 - 2006, Digium, Inc.
5  *
6  * Mark Spencer <markster@digium.com>
7  *
8  * See http://www.asterisk.org for more information about
9  * the Asterisk project. Please do not directly contact
10  * any of the maintainers of this project for assistance;
11  * the project provides a web site, mailing lists and IRC
12  * channels for your use.
13  *
14  * This program is free software, distributed under the terms of
15  * the GNU General Public License Version 2. See the LICENSE file
16  * at the top of the source tree.
17  */
18
19 /*! \file
20  *
21  * \brief DAHDI for Pseudo TDM
22  *
23  * \author Mark Spencer <markster@digium.com>
24  *
25  * Connects to the DAHDI telephony library as well as
26  * libpri. Libpri is optional and needed only if you are
27  * going to use ISDN connections.
28  *
29  * You need to install libraries before you attempt to compile
30  * and install the DAHDI channel.
31  *
32  * \par See also
33  * \arg \ref Config_dahdi
34  *
35  * \ingroup channel_drivers
36  *
37  * \todo Deprecate the "musiconhold" configuration option post 1.4
38  */
39
40 /*** MODULEINFO
41         <depend>res_smdi</depend>
42         <depend>dahdi</depend>
43         <depend>tonezone</depend>
44         <use>pri</use>
45         <use>ss7</use>
46         <use>openr2</use>
47  ***/
48
49 #include "asterisk.h"
50
51 ASTERISK_FILE_VERSION(__FILE__, "$Revision$")
52
53 #ifdef __NetBSD__
54 #include <pthread.h>
55 #include <signal.h>
56 #else
57 #include <sys/signal.h>
58 #endif
59 #include <sys/ioctl.h>
60 #include <math.h>
61 #include <ctype.h>
62
63 #include <dahdi/user.h>
64 #include <dahdi/tonezone.h>
65
66 #ifdef HAVE_PRI
67 #include <libpri.h>
68 #endif
69
70 #ifdef HAVE_SS7
71 #include <libss7.h>
72 #endif
73
74 #ifdef HAVE_OPENR2
75 #include <openr2.h>
76 #endif
77
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"
109
110 /*** DOCUMENTATION
111         <application name="DAHDISendKeypadFacility" language="en_US">
112                 <synopsis>
113                         Send digits out of band over a PRI.
114                 </synopsis>
115                 <syntax>
116                         <parameter name="digits" required="true" />
117                 </syntax>
118                 <description>
119                         <para>This application will send the given string of digits in a Keypad
120                         Facility IE over the current channel.</para>
121                 </description>
122         </application>
123         <application name="DAHDISendCallreroutingFacility" language="en_US">
124                 <synopsis>
125                         Send QSIG call rerouting facility over a PRI.
126                 </synopsis>
127                 <syntax argsep=",">
128                         <parameter name="destination" required="true">
129                                 <para>Destination number.</para>
130                         </parameter>
131                         <parameter name="original">
132                                 <para>Original called number.</para>
133                         </parameter>
134                         <parameter name="reason">
135                                 <para>Diversion reason, if not specified defaults to <literal>unknown</literal></para>
136                         </parameter>
137                 </syntax>
138                 <description>
139                         <para>This application will send a Callrerouting Facility IE over the
140                         current channel.</para>
141                 </description>
142         </application>
143         <application name="DAHDIAcceptR2Call" language="en_US">
144                 <synopsis>
145                         Accept an R2 call if its not already accepted (you still need to answer it)
146                 </synopsis>
147                 <syntax>
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>
151                         </parameter>
152                 </syntax>
153                 <description>
154                         <para>This application will Accept the R2 call either with charge or no charge.</para>
155                 </description>
156         </application>
157  ***/
158
159 #define SMDI_MD_WAIT_TIMEOUT 1500 /* 1.5 seconds */
160
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)",
167 "-7.5db (CSU)",
168 "-15db (CSU)",
169 "-22.5db (CSU)"
170 };
171
172 /*! Global jitterbuffer configuration - by default, jb is disabled */
173 static struct ast_jb_conf default_jbconf =
174 {
175         .flags = 0,
176         .max_size = -1,
177         .resync_threshold = -1,
178         .impl = ""
179 };
180 static struct ast_jb_conf global_jbconf;
181
182 /* define this to send PRI user-user information elements */
183 #undef SUPPORT_USERUSER
184
185 /*!
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.
193  */
194 /* #define ZHONE_HACK */
195
196 /*! \note
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.
200  */
201 /* #define DAHDI_CHECK_HOOKSTATE */
202
203 /*! \brief Typically, how many rings before we should send Caller*ID */
204 #define DEFAULT_CIDRINGS 1
205
206 #define CHANNEL_PSEUDO -12
207
208 #define AST_LAW(p) (((p)->law == DAHDI_LAW_ALAW) ? AST_FORMAT_ALAW : AST_FORMAT_ULAW)
209
210
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))
213
214 static const char tdesc[] = "DAHDI Telephony Driver"
215 #if defined(HAVE_PRI) || defined(HAVE_SS7) || defined(HAVE_OPENR2)
216         " w/"
217 #endif
218 #ifdef HAVE_PRI
219         "PRI"
220 #endif
221 #ifdef HAVE_SS7
222         #ifdef HAVE_PRI
223         " & SS7"
224         #else
225         "SS7"
226         #endif
227 #endif
228 #ifdef HAVE_OPENR2
229         #if defined(HAVE_PRI) || defined(HAVE_SS7)
230         " & MFC/R2"
231         #else
232         "MFC/R2"
233         #endif
234 #endif
235 ;
236
237 static const char config[] = "chan_dahdi.conf";
238
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)
267
268 #ifdef LOTS_OF_SPANS
269 #define NUM_SPANS       DAHDI_MAX_SPANS
270 #else
271 #define NUM_SPANS               32
272 #endif
273 #define NUM_DCHANS              4       /*!< No more than 4 d-channels */
274 #define MAX_CHANNELS    672             /*!< No more than a DS3 per trunk group */
275
276 #define CHAN_PSEUDO     -2
277
278 #define DCHAN_PROVISIONED (1 << 0)
279 #define DCHAN_NOTINALARM  (1 << 1)
280 #define DCHAN_UP          (1 << 2)
281
282 #define DCHAN_AVAILABLE (DCHAN_PROVISIONED | DCHAN_NOTINALARM | DCHAN_UP)
283
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)
289
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)
294
295 static char defaultcic[64] = "";
296 static char defaultozz[64] = "";
297
298 static char parkinglot[AST_MAX_EXTENSION] = "";         /*!< Default parking lot for this channel */
299
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;
304 #endif
305
306 static char progzone[10] = "";
307
308 static int usedistinctiveringdetection = 0;
309 static int distinctiveringaftercid = 0;
310
311 static int numbufs = 4;
312
313 static int mwilevel = 512;
314
315 #ifdef HAVE_PRI
316 static struct ast_channel inuse;
317 #ifdef PRI_GETSET_TIMERS
318 static int pritimers[PRI_MAX_TIMERS];
319 #endif
320 static int pridebugfd = -1;
321 static char pridebugfilename[1024] = "";
322 #endif
323
324 /*! \brief Wait up to 16 seconds for first digit (FXO logic) */
325 static int firstdigittimeout = 16000;
326
327 /*! \brief How long to wait for following digits (FXO logic) */
328 static int gendigittimeout = 8000;
329
330 /*! \brief How long to wait for an extra digit, if there is an ambiguous match */
331 static int matchdigittimeout = 3000;
332
333 /*! \brief Protect the interface list (of dahdi_pvt's) */
334 AST_MUTEX_DEFINE_STATIC(iflock);
335
336 /* QSIG channel mapping option types */
337 #define DAHDI_CHAN_MAPPING_PHYSICAL     0
338 #define DAHDI_CHAN_MAPPING_LOGICAL      1
339
340
341 static int ifcount = 0;
342
343 #ifdef HAVE_PRI
344 AST_MUTEX_DEFINE_STATIC(pridebugfdlock);
345 #endif
346
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);
350
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;
359
360 static int restart_monitor(void);
361
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);
363
364 static int dahdi_sendtext(struct ast_channel *c, const char *text);
365
366 static void mwi_event_cb(const struct ast_event *event, void *userdata)
367 {
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. */
372 }
373
374 /*! \brief Avoid the silly dahdi_getevent which ignores a bunch of events */
375 static inline int dahdi_get_event(int fd)
376 {
377         int j;
378         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
379                 return -1;
380         return j;
381 }
382
383 /*! \brief Avoid the silly dahdi_waitevent which ignores a bunch of events */
384 static inline int dahdi_wait_event(int fd)
385 {
386         int i, j = 0;
387         i = DAHDI_IOMUX_SIGEVENT;
388         if (ioctl(fd, DAHDI_IOMUX, &i) == -1)
389                 return -1;
390         if (ioctl(fd, DAHDI_GETEVENT, &j) == -1)
391                 return -1;
392         return j;
393 }
394
395 /*! Chunk size to read -- we use 20ms chunks to make things happy. */
396 #define READ_SIZE 160
397
398 #define MASK_AVAIL              (1 << 0)        /*!< Channel available for PRI use */
399 #define MASK_INUSE              (1 << 1)        /*!< Channel currently in use */
400
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 */
406
407 struct dahdi_pvt;
408
409 /*!
410  * \brief Configured ring timeout base.
411  * \note Value computed from "ringtimeout" read in from chan_dahdi.conf if it exists.
412  */
413 static int ringt_base = DEFAULT_RINGT;
414
415 #ifdef HAVE_SS7
416
417 #define LINKSTATE_INALARM       (1 << 0)
418 #define LINKSTATE_STARTING      (1 << 1)
419 #define LINKSTATE_UP            (1 << 2)
420 #define LINKSTATE_DOWN          (1 << 3)
421
422 #define SS7_NAI_DYNAMIC         -1
423
424 #define LINKSET_FLAG_EXPLICITACM (1 << 0)
425
426 struct dahdi_ss7 {
427         pthread_t master;                                               /*!< Thread of master */
428         ast_mutex_t lock;
429         int fds[NUM_DCHANS];
430         int numsigchans;
431         int linkstate[NUM_DCHANS];
432         int numchans;
433         int type;
434         enum {
435                 LINKSET_STATE_DOWN = 0,
436                 LINKSET_STATE_UP
437         } state;
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 */
444         struct ss7 *ss7;
445         struct dahdi_pvt *pvts[MAX_CHANNELS];                           /*!< Member channel pvt structs */
446         int flags;                                                      /*!< Linkset flags */
447 };
448
449 static struct dahdi_ss7 linksets[NUM_SPANS];
450
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 */
459
460 #ifdef HAVE_OPENR2
461 struct dahdi_mfcr2 {
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 */
469
470 };
471 struct dahdi_mfcr2_conf {
472         openr2_variant_t variant;
473         int mfback_timeout;
474         int metering_pulse_timeout;
475         int max_ani;
476         int max_dnis;
477         int get_ani_first:1;
478         int call_files:1;
479         int allow_collect_calls:1;
480         int charge_calls:1;
481         int accept_on_offer:1;
482         int forced_release:1;
483         int double_answer: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;
489 };
490
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;
495
496 #endif /* HAVE_OPENR2 */
497
498 #ifdef HAVE_PRI
499
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)
504
505 struct dahdi_pri {
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) */
536         int debug;
537         int fds[NUM_DCHANS];                                            /*!< FD's for d-channels */
538         /*! \brief Value set but not used */
539         int offset;
540         /*! \brief Span number put into user output messages */
541         int span;
542         /*! \brief TRUE if span is being reset/restarted */
543         int resetting;
544         /*! \brief Current position during a reset (-1 if not started) */
545         int resetpos;
546 #ifdef HAVE_PRI_INBANDDISCONNECT
547         unsigned int inbanddisconnect:1;                                /*!< Should we support inband audio after receiving DISCONNECT? */
548 #endif
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...) */
552         int sig;
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 */
556 };
557
558
559 static struct dahdi_pri pris[NUM_SPANS];
560
561 #if 0
562 #define DEFAULT_PRI_DEBUG (PRI_DEBUG_Q931_DUMP | PRI_DEBUG_Q921_DUMP | PRI_DEBUG_Q921_RAW | PRI_DEBUG_Q921_STATE)
563 #else
564 #define DEFAULT_PRI_DEBUG 0
565 #endif
566
567 static inline void pri_rel(struct dahdi_pri *pri)
568 {
569         ast_mutex_unlock(&pri->lock);
570 }
571
572 #else
573 /*! Shut up the compiler */
574 struct dahdi_pri;
575 #endif
576
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 */
580
581 /* Polarity states */
582 #define POLARITY_IDLE   0
583 #define POLARITY_REV    1
584
585
586 struct distRingData {
587         int ring[3];
588         int range;
589 };
590 struct ringContextData {
591         char contextData[AST_MAX_CONTEXT];
592 };
593 struct dahdi_distRings {
594         struct distRingData ringnum[3];
595         struct ringContextData ringContext[3];
596 };
597
598 static char *subnames[] = {
599         "Real",
600         "Callwait",
601         "Threeway"
602 };
603
604 struct dahdi_subchannel {
605         int dfd;
606         struct ast_channel *owner;
607         int chan;
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;
621 };
622
623 #define CONF_USER_REAL          (1 << 0)
624 #define CONF_USER_THIRDCALL     (1 << 1)
625
626 #define MAX_SLAVES      4
627
628 /* States for sending MWI message
629  * First three states are required for send Ring Pulse Alert Signal
630  */
631 typedef enum {
632         MWI_SEND_NULL = 0,
633         MWI_SEND_SA,
634         MWI_SEND_SA_WAIT,
635         MWI_SEND_PAUSE,
636         MWI_SEND_SPILL,
637         MWI_SEND_CLEANUP,
638         MWI_SEND_DONE,
639 } mwisend_states;
640
641 struct mwisend_info {
642         struct  timeval pause;
643         mwisend_states  mwisend_current;
644 };
645
646 static struct dahdi_pvt {
647         ast_mutex_t lock;
648         struct ast_channel *owner;                      /*!< Our current active owner (if applicable) */
649                                                         /*!< Up to three channels can be associated with this call */
650
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 */
654
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 */
658
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 */
665         /*!
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.
668          */
669         int radio;
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 */
674         float cid_rxgain;
675         /*! \brief Rx gain set by chan_dahdi.conf */
676         float rxgain;
677         /*! \brief Tx gain set by chan_dahdi.conf */
678         float txgain;
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 */
682
683         /* flags */
684
685         /*!
686          * \brief TRUE if ADSI (Analog Display Services Interface) available
687          * \note Set from the "adsi" value read in from chan_dahdi.conf
688          */
689         unsigned int adsi:1;
690         /*!
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
694          */
695         unsigned int answeronpolarityswitch:1;
696         /*!
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
700          */
701         unsigned int busydetect:1;
702         /*!
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
706          */
707         unsigned int callreturn:1;
708         /*!
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
713          */
714         unsigned int callwaiting:1;
715         /*!
716          * \brief TRUE if send caller ID for Call Waiting
717          * \note Set from the "callwaitingcallerid" value read in from chan_dahdi.conf
718          */
719         unsigned int callwaitingcallerid:1;
720         /*!
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
725          */
726         unsigned int cancallforward:1;
727         /*!
728          * \brief TRUE if support for call parking is enabled.
729          * \note Set from the "canpark" value read in from chan_dahdi.conf
730          */
731         unsigned int canpark:1;
732         /*! \brief TRUE if to wait for a DTMF digit to confirm answer */
733         unsigned int confirmanswer:1;
734         /*!
735          * \brief TRUE if the channel is to be destroyed on hangup.
736          * (Used by pseudo channels.)
737          */
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. */
747         unsigned int dnd:1;
748         /*! \brief XXX BOOLEAN Purpose??? */
749         unsigned int echobreak:1;
750         /*!
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.
754          */
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;
766         /*!
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
769          */
770         unsigned int hanguponpolarityswitch:1;
771         /*! \brief TRUE if DTMF detection needs to be done by hardware. */
772         unsigned int hardwaredtmf:1;
773         /*!
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
778          */
779         unsigned int hidecallerid:1;
780         /*!
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
784          */
785         unsigned int hidecalleridname:1;
786         /*! \brief TRUE if DTMF detection is disabled. */
787         unsigned int ignoredtmf:1;
788         /*!
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
792          */
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 */
797         unsigned int mate:1;
798         /*! \brief TRUE if we originated the call leg. */
799         unsigned int outgoing:1;
800         /* unsigned int overlapdial:1;                  unused and potentially confusing */
801         /*!
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
805          */
806         unsigned int permcallwaiting:1;
807         /*!
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
810          */
811         unsigned int permhidecallerid:1;
812         /*!
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
815          */
816         unsigned int priindication_oob:1;
817         /*!
818          * \brief TRUE if PRI B channels are always exclusively selected.
819          * \note Set from the "priexclusive" value read in from chan_dahdi.conf
820          */
821         unsigned int priexclusive:1;
822         /*!
823          * \brief TRUE if we will pulse dial.
824          * \note Set from the "pulsedial" value read in from chan_dahdi.conf
825          */
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 */
830         /*!
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
834          */
835         unsigned int restrictcid:1;
836         /*!
837          * \brief TRUE if three way calling is enabled
838          * \note Set from the "threewaycalling" value read in from chan_dahdi.conf
839          */
840         unsigned int threewaycalling:1;
841         /*!
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
848          */
849         unsigned int transfer:1;
850         /*!
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
856          */
857         unsigned int use_callerid:1;
858         /*!
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
863          */
864         unsigned int use_callingpres:1;
865         /*!
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
869          */
870         unsigned int usedistinctiveringdetection:1;
871         /*!
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
874          */
875         unsigned int dahditrcallerid:1;
876         /*!
877          * \brief TRUE if allowed to flash-transfer to busy channels.
878          * \note Set from the "transfertobusy" value read in from chan_dahdi.conf
879          */
880         unsigned int transfertobusy:1;
881         /*!
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
884          */
885         unsigned int mwimonitor_neon:1;
886         /*!
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
889          */
890         unsigned int mwimonitor_fsk:1;
891         /*!
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
895          */
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;
901         /*!
902          * \brief TRUE if channel is out of reset and ready
903          * \note Set but not used.
904          */
905         unsigned int inservice:1;
906         /*!
907          * \brief TRUE if the channel is locally blocked.
908          * \note Applies to SS7 channels.
909          */
910         unsigned int locallyblocked:1;
911         /*!
912          * \brief TRUE if the channel is remotely blocked.
913          * \note Applies to SS7 channels.
914          */
915         unsigned int remotelyblocked:1;
916 #if defined(HAVE_PRI) || defined(HAVE_SS7)
917         /*!
918          * \brief XXX BOOLEAN Purpose???
919          * \note Applies to SS7 channels.
920          */
921         unsigned int rlt:1;
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;
926         /*!
927          * \brief TRUE if this is an idle call
928          * \note Applies to PRI channels.
929          */
930         unsigned int isidlecall:1;
931         /*!
932          * \brief TRUE if call is in a proceeding state.
933          * The call has started working its way through the network.
934          */
935         unsigned int proceeding:1;
936         /*! \brief TRUE if the call has seen progress through the network. */
937         unsigned int progress:1;
938         /*!
939          * \brief TRUE if this channel is being reset/restarted
940          * \note Applies to PRI channels.
941          */
942         unsigned int resetting:1;
943         /*!
944          * \brief TRUE if this channel has received a SETUP_ACKNOWLEDGE
945          * \note Applies to PRI channels.
946          */
947         unsigned int setup_ack:1;
948 #endif
949         /*!
950          * \brief TRUE if SMDI (Simplified Message Desk Interface) is enabled
951          * \note Set from the "usesmdi" value read in from chan_dahdi.conf
952          */
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;
957
958         /*! \brief Distinctive Ring data */
959         struct dahdi_distRings drings;
960
961         /*!
962          * \brief The configured context for incoming calls.
963          * \note The "context" string read in from chan_dahdi.conf
964          */
965         char context[AST_MAX_CONTEXT];
966         /*!
967          * \brief Saved context string.
968          */
969         char defcontext[AST_MAX_CONTEXT];
970         /*! \brief Extension to use in the dialplan. */
971         char exten[AST_MAX_EXTENSION];
972         /*!
973          * \brief Language configured for calls.
974          * \note The "language" string read in from chan_dahdi.conf
975          */
976         char language[MAX_LANGUAGE];
977         /*!
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
980          */
981         char mohinterpret[MAX_MUSICCLASS];
982         /*!
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
985          */
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];
991 #endif
992         /*! \brief Automatic Number Identification code from PRI */
993         int cid_ani2;
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. */
997         int cid_ton;
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];
1014         /*!
1015          * \brief Bitmapped groups this belongs to.
1016          * \note The "group" bitmapped group string read in from chan_dahdi.conf
1017          */
1018         ast_group_t group;
1019         /*! \brief Active PCM encoding format: DAHDI_LAW_ALAW or DAHDI_LAW_MULAW */
1020         int law;
1021         int confno;                                     /*!< Our conference */
1022         int confusers;                                  /*!< Who is using our conference */
1023         int propconfno;                                 /*!< Propagated conference number */
1024         /*!
1025          * \brief Bitmapped call groups this belongs to.
1026          * \note The "callgroup" bitmapped group string read in from chan_dahdi.conf
1027          */
1028         ast_group_t callgroup;
1029         /*!
1030          * \brief Bitmapped pickup groups this belongs to.
1031          * \note The "pickupgroup" bitmapped group string read in from chan_dahdi.conf
1032          */
1033         ast_group_t pickupgroup;
1034         /*!
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
1037          */
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. */
1050         int cidpos;
1051         /*! \brief Length of the cidspill buffer containing samples. */
1052         int cidlen;
1053         /*! \brief Ring timeout timer?? */
1054         int ringt;
1055         /*!
1056          * \brief Ring timeout base.
1057          * \note Value computed indirectly from "ringtimeout" read in from chan_dahdi.conf
1058          */
1059         int ringt_base;
1060         /*!
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.
1065          */
1066         int stripmsd;
1067         /*! \brief BOOLEAN. XXX Meaning what?? */
1068         int callwaitcas;
1069         /*! \brief Number of call waiting rings. */
1070         int callwaitrings;
1071         /*! \brief Echo cancel parameters. */
1072         struct {
1073                 struct dahdi_echocanparams head;
1074                 struct dahdi_echocanparam params[DAHDI_MAX_ECHOCANPARAMS];
1075         } echocancel;
1076         /*!
1077          * \brief Echo training time. 0 = disabled
1078          * \note Set from the "echotraining" value read in from chan_dahdi.conf
1079          */
1080         int echotraining;
1081         /*! \brief Filled with 'w'.  XXX Purpose?? */
1082         char echorest[20];
1083         /*!
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
1086          */
1087         int busycount;
1088         /*!
1089          * \brief Length of "busy" tone on time.
1090          * \note Set from the "busypattern" value read in from chan_dahdi.conf
1091          */
1092         int busy_tonelength;
1093         /*!
1094          * \brief Length of "busy" tone off time.
1095          * \note Set from the "busypattern" value read in from chan_dahdi.conf
1096          */
1097         int busy_quietlength;
1098         /*!
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
1101          */
1102         int callprogress;
1103         /*!
1104          * \brief Number of milliseconds to wait for dialtone.
1105          * \note Set from the "waitfordialtone" value read in from chan_dahdi.conf
1106          */
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. */
1117         char finaldial[64];
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];
1123         /*!
1124          * \brief Voice mailbox location.
1125          * \note Set from the "mailbox" string read in from chan_dahdi.conf
1126          */
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. */
1131         char dialdest[256];
1132         /*! \brief Time the interface went on-hook. */
1133         int onhooktime;
1134         /*! \brief TRUE if the FXS port is off-hook */
1135         int fxsoffhookstate;
1136         /*! \brief -1 = unknown, 0 = no messages, 1 = new messages available */
1137         int msgstate;
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 */
1142 #endif
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. */
1147         int fake_event;
1148         /*!
1149          * \brief Minimal time period (ms) between the answer polarity
1150          * switch and hangup polarity switch.
1151          */
1152         int polarityonanswerdelay;
1153         /*! \brief Start delay time if polarityonanswerdelay is nonzero. */
1154         struct timeval polaritydelaytv;
1155         /*!
1156          * \brief Send caller ID after this many rings.
1157          * \note Set from the "sendcalleridafter" value read in from chan_dahdi.conf
1158          */
1159         int sendcalleridafter;
1160 #ifdef HAVE_PRI
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 */
1168         q931_call *call;
1169         /*! \brief Channel number in span. */
1170         int prioffset;
1171         /*! \brief Logical span number within trunk group */
1172         int logicalspan;
1173 #endif
1174         /*! \brief Current line interface polarity. POLARITY_IDLE, POLARITY_REV */
1175         int polarity;
1176         /*! \brief DSP feature flags: DSP_FEATURE_xxx */
1177         int dsp_features;
1178 #ifdef HAVE_SS7
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;
1203         int transcap;
1204         int cic;                                                        /*!< CIC associated with channel */
1205         unsigned int dpc;                                               /*!< CIC's DPC */
1206         unsigned int loopedback:1;
1207 #endif
1208 #ifdef HAVE_OPENR2
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;
1215         int mfcr2call:1;
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;
1223 #endif
1224         /*! \brief DTMF digit in progress.  0 when no digit in progress. */
1225         char begindigit;
1226         /*! \brief TRUE if confrence is muted. */
1227         int muting;
1228 } *iflist = NULL, *ifend = NULL;
1229
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.
1233  *
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)
1237  *
1238  * \see dahdi_chan_init for the default values.
1239  */
1240 struct dahdi_chan_conf {
1241         struct dahdi_pvt chan;
1242 #ifdef HAVE_PRI
1243         struct dahdi_pri pri;
1244 #endif
1245
1246 #ifdef HAVE_SS7
1247         struct dahdi_ss7 ss7;
1248 #endif
1249
1250 #ifdef HAVE_OPENR2
1251         struct dahdi_mfcr2_conf mfcr2;
1252 #endif
1253         struct dahdi_params timing;
1254         int is_sig_auto; /*!< Use channel signalling from DAHDI? */
1255
1256         /*!
1257          * \brief The serial port to listen for SMDI data on
1258          * \note Set from the "smdiport" string read in from chan_dahdi.conf
1259          */
1260         char smdi_port[SMDI_MAX_FILENAME_LEN];
1261 };
1262
1263 /*! returns a new dahdi_chan_conf with default values (by-value) */
1264 static struct dahdi_chan_conf dahdi_chan_conf_default(void)
1265 {
1266         /* recall that if a field is not included here it is initialized
1267          * to 0 or equivalent
1268          */
1269         struct dahdi_chan_conf conf = {
1270 #ifdef HAVE_PRI
1271                 .pri = {
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,
1278
1279                         .minunused = 2,
1280                         .idleext = "",
1281                         .idledial = "",
1282                         .internationalprefix = "",
1283                         .nationalprefix = "",
1284                         .localprefix = "",
1285                         .privateprefix = "",
1286                         .unknownprefix = "",
1287                         .resetinterval = -1,
1288                 },
1289 #endif
1290 #ifdef HAVE_SS7
1291                 .ss7 = {
1292                         .called_nai = SS7_NAI_NATIONAL,
1293                         .calling_nai = SS7_NAI_NATIONAL,
1294                         .internationalprefix = "",
1295                         .nationalprefix = "",
1296                         .subscriberprefix = "",
1297                         .unknownprefix = ""
1298                 },
1299 #endif
1300 #ifdef HAVE_OPENR2
1301                 .mfcr2 = {
1302                         .variant = OR2_VAR_ITU,
1303                         .mfback_timeout = -1,
1304                         .metering_pulse_timeout = -1,
1305                         .max_ani = 10,
1306                         .max_dnis = 4,
1307                         .get_ani_first = -1,
1308                         .call_files = 0,
1309                         .allow_collect_calls = 0,
1310                         .charge_calls = 1,
1311                         .accept_on_offer = 1,
1312                         .forced_release = 0,
1313                         .double_answer = 0,
1314                         .immediate_accept = -1,
1315                         .logdir = "",
1316                         .r2proto_file = "",
1317                         .loglevel = OR2_LOG_ERROR | OR2_LOG_WARNING,
1318                         .category = OR2_CALLING_PARTY_CATEGORY_NATIONAL_SUBSCRIBER
1319                 },
1320 #endif
1321                 .chan = {
1322                         .context = "default",
1323                         .cid_num = "",
1324                         .cid_name = "",
1325                         .mohinterpret = "default",
1326                         .mohsuggest = "",
1327                         .parkinglot = "",
1328                         .transfertobusy = 1,
1329
1330                         .cid_signalling = CID_SIG_BELL,
1331                         .cid_start = CID_START_RING,
1332                         .dahditrcallerid = 0,
1333                         .use_callerid = 1,
1334                         .sig = -1,
1335                         .outsigmod = -1,
1336
1337                         .cid_rxgain = +5.0,
1338
1339                         .tonezone = -1,
1340
1341                         .echocancel.head.tap_length = 1,
1342
1343                         .busycount = 3,
1344
1345                         .accountcode = "",
1346
1347                         .mailbox = "",
1348
1349 #ifdef HAVE_DAHDI_LINEREVERSE_VMWI
1350                         .mwisend_fsk = 1,
1351 #endif
1352                         .polarityonanswerdelay = 600,
1353
1354                         .sendcalleridafter = DEFAULT_CIDRINGS,
1355
1356                         .buf_policy = DAHDI_POLICY_IMMEDIATE,
1357                         .buf_no = numbufs,
1358                         .usefaxbuffers = 0,
1359                         .faxbuf_policy = DAHDI_POLICY_IMMEDIATE,
1360                         .faxbuf_no = numbufs,
1361                 },
1362                 .timing = {
1363                         .prewinktime = -1,
1364                         .preflashtime = -1,
1365                         .winktime = -1,
1366                         .flashtime = -1,
1367                         .starttime = -1,
1368                         .rxwinktime = -1,
1369                         .rxflashtime = -1,
1370                         .debouncetime = -1
1371                 },
1372                 .is_sig_auto = 1,
1373                 .smdi_port = "/dev/ttyS0",
1374         };
1375
1376         return conf;
1377 }
1378
1379
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);
1395
1396 static const struct ast_channel_tech dahdi_tech = {
1397         .type = "DAHDI",
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,
1404         .call = dahdi_call,
1405         .hangup = dahdi_hangup,
1406         .answer = dahdi_answer,
1407         .read = dahdi_read,
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,
1415 };
1416
1417 #ifdef HAVE_PRI
1418 #define GET_CHANNEL(p) ((p)->bearer ? (p)->bearer->channel : p->channel)
1419 #else
1420 #define GET_CHANNEL(p) ((p)->channel)
1421 #endif
1422
1423 struct dahdi_pvt *round_robin[32];
1424
1425 #if defined(HAVE_PRI)
1426 static inline int pri_grab(struct dahdi_pvt *pvt, struct dahdi_pri *pri)
1427 {
1428         int res;
1429         /* Grab the lock first */
1430         do {
1431                 res = ast_mutex_trylock(&pri->lock);
1432                 if (res) {
1433                         DEADLOCK_AVOIDANCE(&pvt->lock);
1434                 }
1435         } while (res);
1436         /* Then break the poll */
1437         if (pri->master != AST_PTHREADT_NULL)
1438                 pthread_kill(pri->master, SIGURG);
1439         return 0;
1440 }
1441 #endif  /* defined(HAVE_PRI) */
1442
1443 #if defined(HAVE_SS7)
1444 static inline void ss7_rel(struct dahdi_ss7 *ss7)
1445 {
1446         ast_mutex_unlock(&ss7->lock);
1447 }
1448 #endif  /* defined(HAVE_SS7) */
1449
1450 #if defined(HAVE_SS7)
1451 static inline int ss7_grab(struct dahdi_pvt *pvt, struct dahdi_ss7 *pri)
1452 {
1453         int res;
1454         /* Grab the lock first */
1455         do {
1456                 res = ast_mutex_trylock(&pri->lock);
1457                 if (res) {
1458                         DEADLOCK_AVOIDANCE(&pvt->lock);
1459                 }
1460         } while (res);
1461         /* Then break the poll */
1462         if (pri->master != AST_PTHREADT_NULL)
1463                 pthread_kill(pri->master, SIGURG);
1464         return 0;
1465 }
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;
1470
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 */
1476 };
1477
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.
1480  */
1481
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 */
1487 };
1488
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}};
1491
1492 #define ISTRUNK(p) ((p->sig == SIG_FXSLS) || (p->sig == SIG_FXSKS) || \
1493                         (p->sig == SIG_FXSGS) || (p->sig == SIG_PRI))
1494
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) */)
1497
1498 static int dahdi_get_index(struct ast_channel *ast, struct dahdi_pvt *p, int nullok)
1499 {
1500         int res;
1501         if (p->subs[SUB_REAL].owner == ast)
1502                 res = 0;
1503         else if (p->subs[SUB_CALLWAIT].owner == ast)
1504                 res = 1;
1505         else if (p->subs[SUB_THREEWAY].owner == ast)
1506                 res = 2;
1507         else {
1508                 res = -1;
1509                 if (!nullok)
1510                         ast_log(LOG_WARNING, "Unable to get index, and nullok is not asserted\n");
1511         }
1512         return res;
1513 }
1514
1515 static void wakeup_sub(struct dahdi_pvt *p, int a, struct dahdi_pri *pri)
1516 {
1517 #ifdef HAVE_PRI
1518         if (pri)
1519                 ast_mutex_unlock(&pri->lock);
1520 #endif
1521         for (;;) {
1522                 if (p->subs[a].owner) {
1523                         if (ast_channel_trylock(p->subs[a].owner)) {
1524                                 DEADLOCK_AVOIDANCE(&p->lock);
1525                         } else {
1526                                 ast_queue_frame(p->subs[a].owner, &ast_null_frame);
1527                                 ast_channel_unlock(p->subs[a].owner);
1528                                 break;
1529                         }
1530                 } else
1531                         break;
1532         }
1533 #ifdef HAVE_PRI
1534         if (pri)
1535                 ast_mutex_lock(&pri->lock);
1536 #endif
1537 }
1538
1539 static void dahdi_queue_frame(struct dahdi_pvt *p, struct ast_frame *f, void *data)
1540 {
1541 #ifdef HAVE_PRI
1542         struct dahdi_pri *pri = (struct dahdi_pri*) data;
1543 #endif
1544 #ifdef HAVE_SS7
1545         struct dahdi_ss7 *ss7 = (struct dahdi_ss7*) data;
1546 #endif
1547         /* We must unlock the PRI to avoid the possibility of a deadlock */
1548 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1549         if (data) {
1550                 switch (p->sig) {
1551 #ifdef HAVE_PRI
1552                 case SIG_BRI:
1553                 case SIG_BRI_PTMP:
1554                 case SIG_PRI:
1555                         ast_mutex_unlock(&pri->lock);
1556                         break;
1557 #endif
1558 #ifdef HAVE_SS7
1559                 case SIG_SS7:
1560                         ast_mutex_unlock(&ss7->lock);
1561                         break;
1562 #endif
1563                 default:
1564                         break;
1565                 }
1566         }
1567 #endif
1568         for (;;) {
1569                 if (p->owner) {
1570                         if (ast_channel_trylock(p->owner)) {
1571                                 DEADLOCK_AVOIDANCE(&p->lock);
1572                         } else {
1573                                 ast_queue_frame(p->owner, f);
1574                                 ast_channel_unlock(p->owner);
1575                                 break;
1576                         }
1577                 } else
1578                         break;
1579         }
1580 #if defined(HAVE_PRI) || defined(HAVE_SS7)
1581         if (data) {
1582                 switch (p->sig) {
1583 #ifdef HAVE_PRI
1584                 case SIG_BRI:
1585                 case SIG_BRI_PTMP:
1586                 case SIG_PRI:
1587                         ast_mutex_lock(&pri->lock);
1588                         break;
1589 #endif
1590 #ifdef HAVE_SS7
1591                 case SIG_SS7:
1592                         ast_mutex_lock(&ss7->lock);
1593                         break;
1594 #endif
1595                 default:
1596                         break;
1597                 }
1598         }
1599 #endif
1600 }
1601
1602 static struct ast_channel *dahdi_new(struct dahdi_pvt *, int, int, int, int, int);
1603 #ifdef HAVE_OPENR2
1604
1605 static int dahdi_r2_answer(struct dahdi_pvt *p)
1606 {
1607         int res = 0;
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
1610         *  */
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);
1620         } else {
1621                 res = openr2_chan_answer_call_with_mode(p->r2chan, OR2_ANSWER_SIMPLE);
1622         }
1623 #else
1624         res = openr2_chan_answer_call(p->r2chan);
1625 #endif
1626         return res;
1627 }
1628
1629
1630
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)
1633 {
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;
1641         }
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;
1646         }
1647         ast_debug(1, "Using category %s\n", catstr);
1648         return cat;
1649 }
1650
1651 static void dahdi_r2_on_call_init(openr2_chan_t *r2chan)
1652 {
1653         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1654         ast_mutex_lock(&p->lock);
1655         if (p->mfcr2call) {
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));
1663                 return;
1664         }
1665         p->mfcr2call = 1;
1666         /* better safe than sorry ... */
1667         p->cid_name[0] = '\0';
1668         p->cid_num[0] = '\0';
1669         p->rdnis[0] = '\0';
1670         p->exten[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));
1678 }
1679
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)
1683 {
1684         int res;
1685         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1686         ast_mutex_lock(&p->lock);
1687         p->inalarm = alarm ? 1 : 0;
1688         if (p->inalarm) {
1689                 res = get_alarms(p);
1690                 handle_alarms(p, res);
1691         } else {
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);
1694         }
1695         ast_mutex_unlock(&p->lock);
1696 }
1697
1698 static void dahdi_r2_on_os_error(openr2_chan_t *r2chan, int errorcode)
1699 {
1700         ast_log(LOG_ERROR, "OS error on chan %d: %s\n", openr2_chan_get_number(r2chan), strerror(errorcode));
1701 }
1702
1703 static void dahdi_r2_on_protocol_error(openr2_chan_t *r2chan, openr2_protocol_error_t reason)
1704 {
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));
1707         if (p->owner) {
1708                 p->owner->hangupcause = AST_CAUSE_PROTOCOL_ERROR;
1709                 p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1710         }
1711         ast_mutex_lock(&p->lock);
1712         p->mfcr2call = 0;
1713         ast_mutex_unlock(&p->lock);
1714 }
1715
1716 static void dahdi_r2_update_monitor_count(struct dahdi_mfcr2 *mfcr2, int increment)
1717 {
1718         ast_mutex_lock(&mfcr2->monitored_count_lock);
1719         if (increment) {
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);
1724                 }
1725         } else {
1726                 mfcr2->monitored_count--;
1727                 if (mfcr2->monitored_count < 0) {
1728                         ast_log(LOG_ERROR, "we have a bug here!.\n");
1729                 }
1730         }
1731         ast_mutex_unlock(&mfcr2->monitored_count_lock);
1732 }
1733
1734 static void dahdi_r2_on_call_offered(openr2_chan_t *r2chan, const char *ani, const char *dnis, openr2_calling_party_category_t category)
1735 {
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);
1746                 return;
1747         }
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");
1753                 p->cid_num[0] = 0;
1754                 p->cid_name[0] = 0;
1755         }
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");
1759                 p->exten[0] = 's';
1760                 p->exten[1] = 0;
1761         }
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);
1767                 return;
1768         }
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);
1772                 if (c) {
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 */
1777                         return;
1778                 }
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);
1784         } else {
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);
1787         }
1788 }
1789
1790 static void dahdi_r2_on_call_end(openr2_chan_t *r2chan)
1791 {
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);
1795         p->mfcr2call = 0;
1796         ast_mutex_unlock(&p->lock);
1797 }
1798
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)
1801 {
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);
1806         dahdi_enable_ec(p);
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));
1818                                 dahdi_r2_answer(p);
1819                         }
1820                         return;
1821                 }
1822                 c = dahdi_new(p, AST_STATE_RING, 1, SUB_REAL, DAHDI_LAW_ALAW, 0);
1823                 if (c) {
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);
1828                         return;
1829                 }
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);
1833                 return;
1834         }
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;
1838         p->dialing = 0;
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);
1842 }
1843
1844 static void dahdi_r2_on_call_answered(openr2_chan_t *r2chan)
1845 {
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;
1849 }
1850
1851 static void dahdi_r2_on_call_read(openr2_chan_t *r2chan, const unsigned char *buf, int buflen)
1852 {
1853         /*ast_log(LOG_DEBUG, "Read data from dahdi channel %d\n", openr2_chan_get_number(r2chan));*/
1854 }
1855
1856 static int dahdi_r2_cause_to_ast_cause(openr2_call_disconnect_cause_t cause)
1857 {
1858         switch (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:
1872         default:
1873                 return AST_CAUSE_NOTDEFINED;
1874         }
1875 }
1876
1877 static void dahdi_r2_on_call_disconnect(openr2_chan_t *r2chan, openr2_call_disconnect_cause_t cause)
1878 {
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);
1882         if (!p->owner) {
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);
1886                 return;
1887         }
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 */
1895                 switch (cause) {
1896                 case OR2_CAUSE_BUSY_NUMBER:
1897                         p->subs[SUB_REAL].needbusy = 1;
1898                         break;
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;
1906                         break;
1907                 default:
1908                         p->owner->_softhangup |= AST_SOFTHANGUP_DEV;
1909                 }
1910                 ast_mutex_unlock(&p->lock);
1911         } else {
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));
1916         }
1917 }
1918
1919 static void dahdi_r2_write_log(openr2_log_level_t level, char *logmessage)
1920 {
1921         switch (level) {
1922         case OR2_LOG_NOTICE:
1923                 ast_log(LOG_NOTICE, "%s", logmessage);
1924                 break;
1925         case OR2_LOG_WARNING:
1926                 ast_log(LOG_WARNING, "%s", logmessage);
1927                 break;
1928         case OR2_LOG_ERROR:
1929                 ast_log(LOG_ERROR, "%s", logmessage);
1930                 break;
1931         case OR2_LOG_STACK_TRACE:
1932         case OR2_LOG_MF_TRACE:
1933         case OR2_LOG_CAS_TRACE:
1934         case OR2_LOG_DEBUG:
1935         case OR2_LOG_EX_DEBUG:
1936                 ast_log(LOG_DEBUG, "%s", logmessage);
1937                 break;
1938         default:
1939                 ast_log(LOG_WARNING, "We should handle logging level %d here.\n", level);
1940                 ast_log(LOG_DEBUG, "%s", logmessage);
1941                 break;
1942         }
1943 }
1944
1945 static void dahdi_r2_on_line_blocked(openr2_chan_t *r2chan)
1946 {
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));
1952 }
1953
1954 static void dahdi_r2_on_line_idle(openr2_chan_t *r2chan)
1955 {
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));
1961 }
1962
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)
1966 {
1967 #define CONTEXT_TAG "Context - "
1968         char logmsg[256];
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);
1973 #undef CONTEXT_TAG
1974 }
1975
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)
1979 {
1980 #define CHAN_TAG "Chan "
1981         char logmsg[256];
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);
1986 }
1987
1988 static int dahdi_r2_on_dnis_digit_received(openr2_chan_t *r2chan, char digit)
1989 {
1990         struct dahdi_pvt *p = openr2_chan_get_client_data(r2chan);
1991         /* if 'immediate' is set, let's stop requesting DNIS */
1992         if (p->immediate) {
1993                 return 0;
1994         }
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)) {
2004                 return 0;
2005         }
2006         /* otherwise keep going */
2007         return 1;
2008 }
2009
2010 static void dahdi_r2_on_ani_digit_received(openr2_chan_t *r2chan, char digit)
2011 {
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;
2018 }
2019
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
2039 };
2040
2041 static inline int16_t dahdi_r2_alaw_to_linear(uint8_t sample)
2042 {
2043         return AST_ALAW(sample);
2044 }
2045
2046 static inline uint8_t dahdi_r2_linear_to_alaw(int sample)
2047 {
2048         return AST_LIN2A(sample);
2049 }
2050
2051 static openr2_transcoder_interface_t dahdi_r2_transcode_iface = {
2052         dahdi_r2_alaw_to_linear,
2053         dahdi_r2_linear_to_alaw
2054 };
2055
2056 #endif /* HAVE_OPENR2 */
2057
2058 static int restore_gains(struct dahdi_pvt *p);
2059
2060 static void swap_subs(struct dahdi_pvt *p, int a, int b)
2061 {
2062         int tchan;
2063         int tinthreeway;
2064         struct ast_channel *towner;
2065
2066         ast_debug(1, "Swapping %d and %d\n", a, b);
2067
2068         tchan = p->subs[a].chan;
2069         towner = p->subs[a].owner;
2070         tinthreeway = p->subs[a].inthreeway;
2071
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;
2075
2076         p->subs[b].chan = tchan;
2077         p->subs[b].owner = towner;
2078         p->subs[b].inthreeway = tinthreeway;
2079
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);
2086 }
2087
2088 static int dahdi_open(char *fn)
2089 {
2090         int fd;
2091         int isnum;
2092         int chan = 0;
2093         int bs;
2094         int x;
2095         isnum = 1;
2096         for (x = 0; x < strlen(fn); x++) {
2097                 if (!isdigit(fn[x])) {
2098                         isnum = 0;
2099                         break;
2100                 }
2101         }
2102         if (isnum) {
2103                 chan = atoi(fn);
2104                 if (chan < 1) {
2105                         ast_log(LOG_WARNING, "Invalid channel number '%s'\n", fn);
2106                         return -1;
2107                 }
2108                 fn = "/dev/dahdi/channel";
2109         }
2110         fd = open(fn, O_RDWR | O_NONBLOCK);
2111         if (fd < 0) {
2112                 ast_log(LOG_WARNING, "Unable to open '%s': %s\n", fn, strerror(errno));
2113                 return -1;
2114         }
2115         if (chan) {
2116                 if (ioctl(fd, DAHDI_SPECIFY, &chan)) {
2117                         x = errno;
2118                         close(fd);
2119                         errno = x;
2120                         ast_log(LOG_WARNING, "Unable to specify channel %d: %s\n", chan, strerror(errno));
2121                         return -1;
2122                 }
2123         }
2124         bs = READ_SIZE;
2125         if (ioctl(fd, DAHDI_SET_BLOCKSIZE, &bs) == -1) {
2126                 ast_log(LOG_WARNING, "Unable to set blocksize '%d': %s\n", bs,  strerror(errno));
2127                 x = errno;
2128                 close(fd);
2129                 errno = x;
2130                 return -1;
2131         }
2132         return fd;
2133 }
2134
2135 static void dahdi_close(int fd)
2136 {
2137         if (fd > 0)
2138                 close(fd);
2139 }
2140
2141 static void dahdi_close_sub(struct dahdi_pvt *chan_pvt, int sub_num)
2142 {
2143         dahdi_close(chan_pvt->subs[sub_num].dfd);
2144         chan_pvt->subs[sub_num].dfd = -1;
2145 }
2146
2147 #if defined(HAVE_PRI)
2148 static void dahdi_close_pri_fd(struct dahdi_pri *pri, int fd_num)
2149 {
2150         dahdi_close(pri->fds[fd_num]);
2151         pri->fds[fd_num] = -1;
2152 }
2153 #endif  /* defined(HAVE_PRI) */
2154
2155 #if defined(HAVE_SS7)
2156 static void dahdi_close_ss7_fd(struct dahdi_ss7 *ss7, int fd_num)
2157 {
2158         dahdi_close(ss7->fds[fd_num]);
2159         ss7->fds[fd_num] = -1;
2160 }
2161 #endif  /* defined(HAVE_SS7) */
2162
2163 static int dahdi_setlinear(int dfd, int linear)
2164 {
2165         int res;
2166         res = ioctl(dfd, DAHDI_SETLINEAR, &linear);
2167         if (res)
2168                 return res;
2169         return 0;
2170 }
2171
2172
2173 static int alloc_sub(struct dahdi_pvt *p, int x)
2174 {
2175         struct dahdi_bufferinfo bi;
2176         int res;
2177         if (p->subs[x].dfd >= 0) {
2178                 ast_log(LOG_WARNING, "%s subchannel of %d already in use\n", subnames[x], p->channel);
2179                 return -1;
2180         }
2181
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));
2185                 return -1;
2186         }
2187
2188         res = ioctl(p->subs[x].dfd, DAHDI_GET_BUFINFO, &bi);
2189         if (!res) {
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);
2194                 if (res < 0) {
2195                         ast_log(LOG_WARNING, "Unable to set buffer policy on channel %d: %s\n", x, strerror(errno));
2196                 }
2197         } else
2198                 ast_log(LOG_WARNING, "Unable to check buffer policy on channel %d: %s\n", x, strerror(errno));
2199
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;
2204                 return -1;
2205         }
2206         ast_debug(1, "Allocated %s subchannel on FD %d channel %d\n", subnames[x], p->subs[x].dfd, p->subs[x].chan);
2207         return 0;
2208 }
2209
2210 static int unalloc_sub(struct dahdi_pvt *p, int x)
2211 {
2212         if (!x) {
2213                 ast_log(LOG_WARNING, "Trying to unalloc the real channel %d?!?\n", p->channel);
2214                 return -1;
2215         }
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));
2224         return 0;
2225 }
2226
2227 static int digit_to_dtmfindex(char digit)
2228 {
2229         if (isdigit(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;
2239         else
2240                 return -1;
2241 }
2242
2243 static int dahdi_digit_begin(struct ast_channel *chan, char digit)
2244 {
2245         struct dahdi_pvt *pvt;
2246         int idx;
2247         int dtmf = -1;
2248
2249         pvt = chan->tech_pvt;
2250
2251         ast_mutex_lock(&pvt->lock);
2252
2253         idx = dahdi_get_index(chan, pvt, 0);
2254
2255         if ((idx != SUB_REAL) || !pvt->owner)
2256                 goto out;
2257
2258 #ifdef HAVE_PRI
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);
2264                                 pri_rel(pvt->pri);
2265                         } else
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) {
2268                         int res;
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';
2273                 }
2274                 goto out;
2275         }
2276 #endif
2277         if ((dtmf = digit_to_dtmfindex(digit)) == -1)
2278                 goto out;
2279
2280         if (pvt->pulse || ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &dtmf)) {
2281                 int res;
2282                 struct dahdi_dialoperation zo = {
2283                         .op = DAHDI_DIAL_OP_APPEND,
2284                 };
2285
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));
2291                 else
2292                         pvt->dialing = 1;
2293         } else {
2294                 ast_debug(1, "Started VLDTMF digit '%c'\n", digit);
2295                 pvt->dialing = 1;
2296                 pvt->begindigit = digit;
2297         }
2298
2299 out:
2300         ast_mutex_unlock(&pvt->lock);
2301
2302         return 0;
2303 }
2304
2305 static int dahdi_digit_end(struct ast_channel *chan, char digit, unsigned int duration)
2306 {
2307         struct dahdi_pvt *pvt;
2308         int res = 0;
2309         int idx;
2310         int x;
2311
2312         pvt = chan->tech_pvt;
2313
2314         ast_mutex_lock(&pvt->lock);
2315
2316         idx = dahdi_get_index(chan, pvt, 0);
2317
2318         if ((idx != SUB_REAL) || !pvt->owner || pvt->pulse)
2319                 goto out;
2320
2321 #ifdef HAVE_PRI
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)
2325                 goto out;
2326 #endif
2327
2328         if (pvt->begindigit) {
2329                 x = -1;
2330                 ast_debug(1, "Ending VLDTMF digit '%c'\n", digit);
2331                 res = ioctl(pvt->subs[SUB_REAL].dfd, DAHDI_SENDTONE, &x);
2332                 pvt->dialing = 0;
2333                 pvt->begindigit = 0;
2334         }
2335
2336 out:
2337         ast_mutex_unlock(&pvt->lock);
2338
2339         return res;
2340 }
2341
2342 static char *events[] = {
2343         "No event",
2344         "On hook",
2345         "Ring/Answered",
2346         "Wink/Flash",
2347         "Alarm",
2348         "No more alarm",
2349         "HDLC Abort",
2350         "HDLC Overrun",
2351         "HDLC Bad FCS",
2352         "Dial Complete",
2353         "Ringer On",
2354         "Ringer Off",
2355         "Hook Transition Complete",
2356         "Bits Changed",
2357         "Pulse Start",
2358         "Timer Expired",
2359         "Timer Ping",
2360         "Polarity Reversal",
2361         "Ring Begin",
2362 };
2363
2364 static struct {
2365         int alarm;
2366         char *name;
2367 } alarms[] = {
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" },
2375 };
2376
2377 static char *alarm2str(int alm)
2378 {
2379         int x;
2380         for (x = 0; x < ARRAY_LEN(alarms); x++) {
2381                 if (alarms[x].alarm & alm)
2382                         return alarms[x].name;
2383         }
2384         return alm ? "Unknown Alarm" : "No Alarm";
2385 }
2386
2387 static char *event2str(int event)
2388 {
2389         static char buf[256];
2390         if ((event < (ARRAY_LEN(events))) && (event > -1))
2391                 return events[event];
2392         sprintf(buf, "Event %d", event); /* safe */
2393         return buf;
2394 }
2395
2396 #ifdef HAVE_PRI
2397 static char *dialplan2str(int dialplan)
2398 {
2399         if (dialplan == -1 || dialplan == -2) {
2400                 return("Dynamically set dialplan in ISDN");
2401         }
2402         return (pri_plan2str(dialplan));
2403 }
2404 #endif
2405
2406 static char *dahdi_sig2str(int sig)
2407 {
2408         static char buf[256];
2409         switch (sig) {
2410         case SIG_EM:
2411                 return "E & M Immediate";
2412         case SIG_EMWINK:
2413                 return "E & M Wink";
2414         case SIG_EM_E1:
2415                 return "E & M E1";
2416         case SIG_FEATD:
2417                 return "Feature Group D (DTMF)";
2418         case SIG_FEATDMF:
2419                 return "Feature Group D (MF)";
2420         case SIG_FEATDMF_TA:
2421                 return "Feature Groud D (MF) Tandem Access";
2422         case SIG_FEATB:
2423                 return "Feature Group B (MF)";
2424         case SIG_E911:
2425                 return "E911 (MF)";
2426         case SIG_FGC_CAMA:
2427                 return "FGC/CAMA (Dialpulse)";
2428         case SIG_FGC_CAMAMF:
2429                 return "FGC/CAMA (MF)";
2430         case SIG_FXSLS:
2431                 return "FXS Loopstart";
2432         case SIG_FXSGS:
2433                 return "FXS Groundstart";
2434         case SIG_FXSKS:
2435                 return "FXS Kewlstart";
2436         case SIG_FXOLS:
2437                 return "FXO Loopstart";
2438         case SIG_FXOGS:
2439                 return "FXO Groundstart";
2440         case SIG_FXOKS:
2441                 return "FXO Kewlstart";
2442         case SIG_PRI:
2443                 return "ISDN PRI";
2444         case SIG_BRI:
2445                 return "ISDN BRI Point to Point";
2446         case SIG_BRI_PTMP:
2447                 return "ISDN BRI Point to MultiPoint";
2448         case SIG_SS7:
2449                 return "SS7";
2450         case SIG_MFCR2:
2451                 return "MFC/R2";
2452         case SIG_SF:
2453                 return "SF (Tone) Immediate";
2454         case SIG_SFWINK:
2455                 return "SF (Tone) Wink";
2456         case SIG_SF_FEATD:
2457                 return "SF (Tone) with Feature Group D (DTMF)";
2458         case SIG_SF_FEATDMF:
2459                 return "SF (Tone) with Feature Group D (MF)";
2460         case SIG_SF_FEATB:
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";
2466         case 0:
2467                 return "Pseudo";
2468         default:
2469                 snprintf(buf, sizeof(buf), "Unknown signalling %d", sig);
2470                 return buf;
2471         }
2472 }
2473
2474 #define sig2str dahdi_sig2str
2475
2476 static int conf_add(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx, int slavechannel)
2477 {
2478         /* If the conference already exists, and we're already in it
2479            don't bother doing anything */
2480         struct dahdi_confinfo zi;
2481
2482         memset(&zi, 0, sizeof(zi));
2483         zi.chan = 0;
2484
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;
2489         } else {
2490                 if (!idx) {
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;
2494                 } else
2495                         zi.confmode = DAHDI_CONF_CONF | DAHDI_CONF_TALKER | DAHDI_CONF_LISTENER;
2496                 zi.confno = p->confno;
2497         }
2498         if ((zi.confno == c->curconf.confno) && (zi.confmode == c->curconf.confmode))
2499                 return 0;
2500         if (c->dfd < 0)
2501                 return 0;
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));
2504                 return -1;
2505         }
2506         if (slavechannel < 1) {
2507                 p->confno = zi.confno;
2508         }
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);
2511         return 0;
2512 }
2513
2514 static int isourconf(struct dahdi_pvt *p, struct dahdi_subchannel *c)
2515 {
2516         /* If they're listening to our channel, they're ours */
2517         if ((p->channel == c->curconf.confno) && (c->curconf.confmode == DAHDI_CONF_DIGITALMON))
2518                 return 1;
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))
2521                 return 1;
2522         return 0;
2523 }
2524
2525 static int conf_del(struct dahdi_pvt *p, struct dahdi_subchannel *c, int idx)
2526 {
2527         struct dahdi_confinfo zi;
2528         if (/* Can't delete if there's no dfd */
2529                 (c->dfd < 0) ||
2530                 /* Don't delete from the conference if it's not our conference */
2531                 !isourconf(p, c)
2532                 /* Don't delete if we don't think it's conferenced at all (implied) */
2533                 ) return 0;
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));
2537                 return -1;
2538         }
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));
2541         return 0;
2542 }
2543
2544 static int isslavenative(struct dahdi_pvt *p, struct dahdi_pvt **out)
2545 {
2546         int x;
2547         int useslavenative;
2548         struct dahdi_pvt *slave = NULL;
2549         /* Start out optimistic */
2550         useslavenative = 1;
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
2554                    of the question */
2555                 if ((p->subs[x].dfd > -1) && p->subs[x].inthreeway)
2556                         useslavenative = 0;
2557         }
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++) {
2562                         if (p->slaves[x]) {
2563                                 if (slave) {
2564                                         /* Whoops already have a slave!  No
2565                                            slave native and stop right away */
2566                                         slave = NULL;
2567                                         useslavenative = 0;
2568                                         break;
2569                                 } else {
2570                                         /* We have one slave so far */
2571                                         slave = p->slaves[x];
2572                                 }
2573                         }
2574                 }
2575         }
2576         /* If no slave, slave native definitely out */
2577         if (!slave)
2578                 useslavenative = 0;
2579         else if (slave->law != p->law) {
2580                 useslavenative = 0;
2581                 slave = NULL;
2582         }
2583         if (out)
2584                 *out = slave;
2585         return useslavenative;
2586 }
2587
2588 static int reset_conf(struct dahdi_pvt *p)
2589 {
2590         p->confno = -1;
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;
2594
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));
2598         }
2599         return 0;
2600 }
2601
2602 static int update_conf(struct dahdi_pvt *p)
2603 {
2604         int needconf = 0;
2605         int x;
2606         int useslavenative;
2607         struct dahdi_pvt *slave = NULL;
2608
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);
2615                         needconf++;
2616                 } else {
2617                         conf_del(p, &p->subs[x], x);
2618                 }
2619         }
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++) {
2623                 if (p->slaves[x]) {
2624                         if (useslavenative)
2625                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p));
2626                         else {
2627                                 conf_add(p, &p->slaves[x]->subs[SUB_REAL], SUB_REAL, 0);
2628                                 needconf++;
2629                         }
2630                 }
2631         }
2632         /* If we're supposed to be in there, do so now */
2633         if (p->inconference && !p->subs[SUB_REAL].inthreeway) {
2634                 if (useslavenative)
2635                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(slave));
2636                 else {
2637                         conf_add(p, &p->subs[SUB_REAL], SUB_REAL, 0);
2638                         needconf++;
2639                 }
2640         }
2641         /* If we have a master, add ourselves to his conference */
2642         if (p->master) {
2643                 if (isslavenative(p->master, NULL)) {
2644                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, GET_CHANNEL(p->master));
2645                 } else {
2646                         conf_add(p->master, &p->subs[SUB_REAL], SUB_REAL, 0);
2647                 }
2648         }
2649         if (!needconf) {
2650                 /* Nobody is left (or should be left) in our conference.
2651                    Kill it. */
2652                 p->confno = -1;
2653         }
2654         ast_debug(1, "Updated conferencing on %d, with %d conference users\n", p->channel, needconf);
2655         return 0;
2656 }
2657
2658 static void dahdi_enable_ec(struct dahdi_pvt *p)
2659 {
2660         int x;
2661         int res;
2662         if (!p)
2663                 return;
2664         if (p->echocanon) {
2665                 ast_debug(1, "Echo cancellation already on\n");
2666                 return;
2667         }
2668         if (p->digital) {
2669                 ast_debug(1, "Echo cancellation isn't required on digital connection\n");
2670                 return;
2671         }
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)) {
2674                         x = 1;
2675                         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &x);
2676                         if (res)
2677                                 ast_log(LOG_WARNING, "Unable to enable audio mode on channel %d (%s)\n", p->channel, strerror(errno));
2678                 }
2679                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &p->echocancel);
2680                 if (res) {
2681                         ast_log(LOG_WARNING, "Unable to enable echo cancellation on channel %d (%s)\n", p->channel, strerror(errno));
2682                 } else {
2683                         p->echocanon = 1;
2684                         ast_debug(1, "Enabled echo cancellation on channel %d\n", p->channel);
2685                 }
2686         } else
2687                 ast_debug(1, "No echo cancellation requested\n");
2688 }
2689
2690 static void dahdi_train_ec(struct dahdi_pvt *p)
2691 {
2692         int x;
2693         int res;
2694
2695         if (p && p->echocanon && p->echotraining) {
2696                 x = p->echotraining;
2697                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOTRAIN, &x);
2698                 if (res)
2699                         ast_log(LOG_WARNING, "Unable to request echo training on channel %d: %s\n", p->channel, strerror(errno));
2700                 else
2701                         ast_debug(1, "Engaged echo training on channel %d\n", p->channel);
2702         } else {
2703                 ast_debug(1, "No echo training requested\n");
2704         }
2705 }
2706
2707 static void dahdi_disable_ec(struct dahdi_pvt *p)
2708 {
2709         int res;
2710
2711         if (p->echocanon) {
2712                 struct dahdi_echocanparams ecp = { .tap_length = 0 };
2713
2714                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_ECHOCANCEL_PARAMS, &ecp);
2715
2716                 if (res)
2717                         ast_log(LOG_WARNING, "Unable to disable echo cancellation on channel %d: %s\n", p->channel, strerror(errno));
2718                 else
2719                         ast_debug(1, "Disabled echo cancellation on channel %d\n", p->channel);
2720         }
2721
2722         p->echocanon = 0;
2723 }
2724
2725 static void fill_txgain(struct dahdi_gains *g, float gain, int law)
2726 {
2727         int j;
2728         int k;
2729         float linear_gain = pow(10.0, gain / 20.0);
2730
2731         switch (law) {
2732         case DAHDI_LAW_ALAW:
2733                 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
2734                         if (gain) {
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);
2739                         } else {
2740                                 g->txgain[j] = j;
2741                         }
2742                 }
2743                 break;
2744         case DAHDI_LAW_MULAW:
2745                 for (j = 0; j < ARRAY_LEN(g->txgain); j++) {
2746                         if (gain) {
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);
2751                         } else {
2752                                 g->txgain[j] = j;
2753                         }
2754                 }
2755                 break;
2756         }
2757 }
2758
2759 static void fill_rxgain(struct dahdi_gains *g, float gain, int law)
2760 {
2761         int j;
2762         int k;
2763         float linear_gain = pow(10.0, gain / 20.0);
2764
2765         switch (law) {
2766         case DAHDI_LAW_ALAW:
2767                 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
2768                         if (gain) {
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);
2773                         } else {
2774                                 g->rxgain[j] = j;
2775                         }
2776                 }
2777                 break;
2778         case DAHDI_LAW_MULAW:
2779                 for (j = 0; j < ARRAY_LEN(g->rxgain); j++) {
2780                         if (gain) {
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);
2785                         } else {
2786                                 g->rxgain[j] = j;
2787                         }
2788                 }
2789                 break;
2790         }
2791 }
2792
2793 static int set_actual_txgain(int fd, int chan, float gain, int law)
2794 {
2795         struct dahdi_gains g;
2796         int res;
2797
2798         memset(&g, 0, sizeof(g));
2799         g.chan = chan;
2800         res = ioctl(fd, DAHDI_GETGAINS, &g);
2801         if (res) {
2802                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
2803                 return res;
2804         }
2805
2806         fill_txgain(&g, gain, law);
2807
2808         return ioctl(fd, DAHDI_SETGAINS, &g);
2809 }
2810
2811 static int set_actual_rxgain(int fd, int chan, float gain, int law)
2812 {
2813         struct dahdi_gains g;
2814         int res;
2815
2816         memset(&g, 0, sizeof(g));
2817         g.chan = chan;
2818         res = ioctl(fd, DAHDI_GETGAINS, &g);
2819         if (res) {
2820                 ast_debug(1, "Failed to read gains: %s\n", strerror(errno));
2821                 return res;
2822         }
2823
2824         fill_rxgain(&g, gain, law);
2825
2826         return ioctl(fd, DAHDI_SETGAINS, &g);
2827 }
2828
2829 static int set_actual_gain(int fd, int chan, float rxgain, float txgain, int law)
2830 {
2831         return set_actual_txgain(fd, chan, txgain, law) | set_actual_rxgain(fd, chan, rxgain, law);
2832 }
2833
2834 static int bump_gains(struct dahdi_pvt *p)
2835 {
2836         int res;
2837
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);
2840         if (res) {
2841                 ast_log(LOG_WARNING, "Unable to bump gain: %s\n", strerror(errno));
2842                 return -1;
2843         }
2844
2845         return 0;
2846 }
2847
2848 static int restore_gains(struct dahdi_pvt *p)
2849 {
2850         int res;
2851
2852         res = set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
2853         if (res) {
2854                 ast_log(LOG_WARNING, "Unable to restore gains: %s\n", strerror(errno));
2855                 return -1;
2856         }
2857
2858         return 0;
2859 }
2860
2861 static inline int dahdi_set_hook(int fd, int hs)
2862 {
2863         int x, res;
2864
2865         x = hs;
2866         res = ioctl(fd, DAHDI_HOOK, &x);
2867
2868         if (res < 0) {
2869                 if (errno == EINPROGRESS)
2870                         return 0;
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 */
2873         }
2874
2875         return res;
2876 }
2877
2878 static inline int dahdi_confmute(struct dahdi_pvt *p, int muted)
2879 {
2880         int x, y, res;
2881         x = muted;
2882         if ((p->sig == SIG_PRI) || (p->sig == SIG_SS7) || (p->sig == SIG_BRI) || (p->sig == SIG_BRI_PTMP)) {
2883                 y = 1;
2884                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_AUDIOMODE, &y);
2885                 if (res)
2886                         ast_log(LOG_WARNING, "Unable to set audio mode on %d: %s\n", p->channel, strerror(errno));
2887         }
2888         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_CONFMUTE, &x);
2889         if (res < 0)
2890                 ast_log(LOG_WARNING, "DAHDI confmute(%d) failed on channel %d: %s\n", muted, p->channel, strerror(errno));
2891         return res;
2892 }
2893
2894 static int save_conference(struct dahdi_pvt *p)
2895 {
2896         struct dahdi_confinfo c;
2897         int res;
2898         if (p->saveconf.confmode) {
2899                 ast_log(LOG_WARNING, "Can't save conference -- already in use\n");
2900                 return -1;
2901         }
2902         p->saveconf.chan = 0;
2903         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_GETCONF, &p->saveconf);
2904         if (res) {
2905                 ast_log(LOG_WARNING, "Unable to get conference info: %s\n", strerror(errno));
2906                 p->saveconf.confmode = 0;
2907                 return -1;
2908         }
2909         memset(&c, 0, sizeof(c));
2910         c.confmode = DAHDI_CONF_NORMAL;
2911         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &c);
2912         if (res) {
2913                 ast_log(LOG_WARNING, "Unable to set conference info: %s\n", strerror(errno));
2914                 return -1;
2915         }
2916         ast_debug(1, "Disabled conferencing\n");
2917         return 0;
2918 }
2919
2920 /*!
2921  * \brief Send MWI state change
2922  *
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.
2927  *
2928  *  \return nothing
2929  *
2930  * This function does two things:
2931  *
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.
2934  *
2935  * 2) It runs the script specified by the mwimonitornotify option to allow
2936  *    some custom handling of the state change.
2937  */
2938 static void notify_message(char *mailbox_full, int thereornot)
2939 {
2940         char s[sizeof(mwimonitornotify) + 80];
2941         struct ast_event *event;
2942         char *mailbox, *context;
2943
2944         /* Strip off @default */
2945         context = mailbox = ast_strdupa(mailbox_full);
2946         strsep(&context, "@");
2947         if (ast_strlen_zero(context))
2948                 context = "default";
2949
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))) {
2956                 return;
2957         }
2958
2959         ast_event_queue_and_cache(event);
2960
2961         if (!ast_strlen_zero(mailbox) && !ast_strlen_zero(mwimonitornotify)) {
2962                 snprintf(s, sizeof(s), "%s %s %d", mwimonitornotify, mailbox, thereornot);
2963                 ast_safe_system(s);
2964         }
2965 }
2966
2967 static int restore_conference(struct dahdi_pvt *p)
2968 {
2969         int res;
2970         if (p->saveconf.confmode) {
2971                 res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_SETCONF, &p->saveconf);
2972                 p->saveconf.confmode = 0;
2973                 if (res) {
2974                         ast_log(LOG_WARNING, "Unable to restore conference info: %s\n", strerror(errno));
2975                         return -1;
2976                 }
2977         }
2978         ast_debug(1, "Restored conferencing\n");
2979         return 0;
2980 }
2981
2982 static int send_callerid(struct dahdi_pvt *p);
2983
2984 static int send_cwcidspill(struct dahdi_pvt *p)
2985 {
2986         p->callwaitcas = 0;
2987         p->cidcwexpire = 0;
2988         if (!(p->cidspill = ast_malloc(MAX_CALLERID_SIZE)))
2989                 return -1;
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;
2993         p->cidpos = 0;
2994         send_callerid(p);
2995         ast_verb(3, "CPE supports Call Waiting Caller*ID.  Sending '%s/%s'\n", p->callwait_name, p->callwait_num);
2996         return 0;
2997 }
2998
2999 static int has_voicemail(struct dahdi_pvt *p)
3000 {
3001         int new_msgs;
3002         struct ast_event *event;
3003         char *mailbox, *context;
3004
3005         mailbox = context = ast_strdupa(p->mailbox);
3006         strsep(&context, "@");
3007         if (ast_strlen_zero(context))
3008                 context = "default";
3009
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,
3013                 AST_EVENT_IE_END);
3014
3015         if (event) {
3016                 new_msgs = ast_event_get_ie_uint(event, AST_EVENT_IE_NEWMSGS);
3017                 ast_event_destroy(event);
3018         } else
3019                 new_msgs = ast_app_has_voicemail(p->mailbox, NULL);
3020
3021         return new_msgs;
3022 }
3023
3024 static int send_callerid(struct dahdi_pvt *p)
3025 {
3026         /* Assumes spill in p->cidspill, p->cidlen in length and we're p->cidpos into it */
3027         int res;
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);
3032         }
3033         while (p->cidpos < p->cidlen) {
3034                 res = write(p->subs[SUB_REAL].dfd, p->cidspill + p->cidpos, p->cidlen - p->cidpos);
3035                 if (res < 0) {
3036                         if (errno == EAGAIN)
3037                                 return 0;
3038                         else {
3039                                 ast_log(LOG_WARNING, "write failed: %s\n", strerror(errno));
3040                                 return -1;
3041                         }
3042                 }
3043                 if (!res)
3044                         return 0;
3045                 p->cidpos += res;
3046         }
3047         ast_free(p->cidspill);
3048         p->cidspill = NULL;
3049         if (p->callwaitcas) {
3050                 /* Wait for CID/CW to expire */
3051                 p->cidcwexpire = CIDCW_EXPIRE_SAMPLES;
3052         } else
3053                 restore_conference(p);
3054         return 0;
3055 }
3056
3057 static int dahdi_callwait(struct ast_channel *ast)
3058 {
3059         struct dahdi_pvt *p = ast->tech_pvt;
3060         p->callwaitingrepeat = CALLWAITING_REPEAT_SAMPLES;
3061         if (p->cidspill) {
3062                 ast_log(LOG_WARNING, "Spill already exists?!?\n");
3063                 ast_free(p->cidspill);
3064         }
3065         if (!(p->cidspill = ast_malloc(2400 /* SAS */ + 680 /* CAS */ + READ_SIZE * 4)))
3066                 return -1;
3067         save_conference(p);
3068         /* Silence */
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));
3072                 p->callwaitcas = 1;
3073                 p->cidlen = 2400 + 680 + READ_SIZE * 4;
3074         } else {
3075                 ast_gen_cas(p->cidspill, 1, 2400, AST_LAW(p));
3076                 p->callwaitcas = 0;
3077                 p->cidlen = 2400 + READ_SIZE * 4;
3078         }
3079         p->cidpos = 0;
3080         send_callerid(p);
3081
3082         return 0;
3083 }
3084
3085 #if defined(HAVE_SS7)
3086 static unsigned char cid_pres2ss7pres(int cid_pres)
3087 {
3088          return (cid_pres >> 5) & 0x03;
3089 }
3090 #endif  /* defined(HAVE_SS7) */
3091
3092 #if defined(HAVE_SS7)
3093 static unsigned char cid_pres2ss7screen(int cid_pres)
3094 {
3095         return cid_pres & 0x03;
3096 }
3097 #endif  /* defined(HAVE_SS7) */
3098
3099 static int dahdi_call(struct ast_channel *ast, char *rdest, int timeout)
3100 {
3101         struct dahdi_pvt *p = ast->tech_pvt;
3102         int x, res, idx,mysig;
3103         char *c, *n, *l;
3104 #ifdef HAVE_PRI
3105         char *s = NULL;
3106 #endif
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);
3114                 return 0;
3115         }
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);
3119                 return -1;
3120         }
3121         p->waitingfordt.tv_sec = 0;
3122         p->dialednone = 0;
3123         if ((p->radio || (p->oprmode < 0)))  /* if a radio channel, up immediately */
3124         {
3125                 /* Special pseudo -- automatically up */
3126                 ast_setstate(ast, AST_STATE_UP);
3127                 ast_mutex_unlock(&p->lock);
3128                 return 0;
3129         }
3130         x = DAHDI_FLUSH_READ | DAHDI_FLUSH_WRITE;
3131         res = ioctl(p->subs[SUB_REAL].dfd, DAHDI_FLUSH, &x);
3132         if (res)
3133                 ast_log(LOG_WARNING, "Unable to flush input on channel %d: %s\n", p->channel, strerror(errno));
3134         p->outgoing = 1;
3135
3136         set_actual_gain(p->subs[SUB_REAL].dfd, 0, p->rxgain, p->txgain, p->law);
3137
3138         mysig = p->sig;
3139         if (p->outsigmod > -1)
3140                 mysig = p->outsigmod;
3141
3142         switch (mysig) {
3143         case SIG_FXOLS:
3144         case SIG_FXOGS:
3145         case SIG_FXOKS:
3146                 if (p->owner == ast) {
3147                         /* Normal ring, on hook */
3148
3149                         /* Don't send audio while on hook, until the call is answered */
3150                         p->dialing = 1;
3151                         if (p->use_callerid) {
3152                                 /* Generate the Caller-ID spill if desired */
3153                                 if (p->cidspill) {
3154                                         ast_log(LOG_WARNING, "cidspill already exists??\n");
3155                                         ast_free(p->cidspill);
3156                                 }
3157                                 p->callwaitcas = 0;
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));
3160                                         p->cidpos = 0;
3161                                         send_callerid(p);
3162                                 }
3163                         }
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];
3169                         } else {
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;
3173